babylon.max.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683
  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(BABYLON) {
  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 "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5407. */
  5408. Matrix.Lerp = function (startValue, endValue, gradient) {
  5409. var result = Matrix.Zero();
  5410. for (var index = 0; index < 16; index++) {
  5411. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5412. }
  5413. result._markAsUpdated();
  5414. return result;
  5415. };
  5416. /**
  5417. * Returns a new Matrix whose values are computed by :
  5418. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5419. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5420. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5421. */
  5422. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5423. var startScale = new Vector3(0, 0, 0);
  5424. var startRotation = new Quaternion();
  5425. var startTranslation = new Vector3(0, 0, 0);
  5426. startValue.decompose(startScale, startRotation, startTranslation);
  5427. var endScale = new Vector3(0, 0, 0);
  5428. var endRotation = new Quaternion();
  5429. var endTranslation = new Vector3(0, 0, 0);
  5430. endValue.decompose(endScale, endRotation, endTranslation);
  5431. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5432. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5433. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5434. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5435. };
  5436. /**
  5437. * 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".
  5438. * This methods works for a Left-Handed system.
  5439. */
  5440. Matrix.LookAtLH = function (eye, target, up) {
  5441. var result = Matrix.Zero();
  5442. Matrix.LookAtLHToRef(eye, target, up, result);
  5443. return result;
  5444. };
  5445. /**
  5446. * 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".
  5447. * This methods works for a Left-Handed system.
  5448. */
  5449. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5450. // Z axis
  5451. target.subtractToRef(eye, this._zAxis);
  5452. this._zAxis.normalize();
  5453. // X axis
  5454. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5455. if (this._xAxis.lengthSquared() === 0) {
  5456. this._xAxis.x = 1.0;
  5457. }
  5458. else {
  5459. this._xAxis.normalize();
  5460. }
  5461. // Y axis
  5462. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5463. this._yAxis.normalize();
  5464. // Eye angles
  5465. var ex = -Vector3.Dot(this._xAxis, eye);
  5466. var ey = -Vector3.Dot(this._yAxis, eye);
  5467. var ez = -Vector3.Dot(this._zAxis, eye);
  5468. 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);
  5469. };
  5470. /**
  5471. * 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".
  5472. * This methods works for a Right-Handed system.
  5473. */
  5474. Matrix.LookAtRH = function (eye, target, up) {
  5475. var result = Matrix.Zero();
  5476. Matrix.LookAtRHToRef(eye, target, up, result);
  5477. return result;
  5478. };
  5479. /**
  5480. * 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".
  5481. * This methods works for a Left-Handed system.
  5482. */
  5483. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5484. // Z axis
  5485. eye.subtractToRef(target, this._zAxis);
  5486. this._zAxis.normalize();
  5487. // X axis
  5488. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5489. if (this._xAxis.lengthSquared() === 0) {
  5490. this._xAxis.x = 1.0;
  5491. }
  5492. else {
  5493. this._xAxis.normalize();
  5494. }
  5495. // Y axis
  5496. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5497. this._yAxis.normalize();
  5498. // Eye angles
  5499. var ex = -Vector3.Dot(this._xAxis, eye);
  5500. var ey = -Vector3.Dot(this._yAxis, eye);
  5501. var ez = -Vector3.Dot(this._zAxis, eye);
  5502. 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);
  5503. };
  5504. /**
  5505. * 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.
  5506. */
  5507. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5508. var matrix = Matrix.Zero();
  5509. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5510. return matrix;
  5511. };
  5512. /**
  5513. * 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.
  5514. */
  5515. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5516. var n = znear;
  5517. var f = zfar;
  5518. var a = 2.0 / width;
  5519. var b = 2.0 / height;
  5520. var c = 2.0 / (f - n);
  5521. var d = -(f + n) / (f - n);
  5522. 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);
  5523. };
  5524. /**
  5525. * 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.
  5526. */
  5527. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5528. var matrix = Matrix.Zero();
  5529. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5530. return matrix;
  5531. };
  5532. /**
  5533. * 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.
  5534. */
  5535. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5536. var n = znear;
  5537. var f = zfar;
  5538. var a = 2.0 / (right - left);
  5539. var b = 2.0 / (top - bottom);
  5540. var c = 2.0 / (f - n);
  5541. var d = -(f + n) / (f - n);
  5542. var i0 = (left + right) / (left - right);
  5543. var i1 = (top + bottom) / (bottom - top);
  5544. 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);
  5545. };
  5546. /**
  5547. * 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.
  5548. */
  5549. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5550. var matrix = Matrix.Zero();
  5551. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5552. return matrix;
  5553. };
  5554. /**
  5555. * 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.
  5556. */
  5557. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5558. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5559. result.m[10] *= -1.0;
  5560. };
  5561. /**
  5562. * 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.
  5563. */
  5564. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. var n = znear;
  5567. var f = zfar;
  5568. var a = 2.0 * n / width;
  5569. var b = 2.0 * n / height;
  5570. var c = (f + n) / (f - n);
  5571. var d = -2.0 * f * n / (f - n);
  5572. 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);
  5573. return matrix;
  5574. };
  5575. /**
  5576. * 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.
  5577. */
  5578. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5579. var matrix = Matrix.Zero();
  5580. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5581. return matrix;
  5582. };
  5583. /**
  5584. * 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.
  5585. */
  5586. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5588. var n = znear;
  5589. var f = zfar;
  5590. var t = 1.0 / (Math.tan(fov * 0.5));
  5591. var a = isVerticalFovFixed ? (t / aspect) : t;
  5592. var b = isVerticalFovFixed ? t : (t * aspect);
  5593. var c = (f + n) / (f - n);
  5594. var d = -2.0 * f * n / (f - n);
  5595. 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);
  5596. };
  5597. /**
  5598. * 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.
  5599. */
  5600. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5601. var matrix = Matrix.Zero();
  5602. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5603. return matrix;
  5604. };
  5605. /**
  5606. * 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.
  5607. */
  5608. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5609. //alternatively this could be expressed as:
  5610. // m = PerspectiveFovLHToRef
  5611. // m[10] *= -1.0;
  5612. // m[11] *= -1.0;
  5613. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5614. var n = znear;
  5615. var f = zfar;
  5616. var t = 1.0 / (Math.tan(fov * 0.5));
  5617. var a = isVerticalFovFixed ? (t / aspect) : t;
  5618. var b = isVerticalFovFixed ? t : (t * aspect);
  5619. var c = -(f + n) / (f - n);
  5620. var d = -2 * f * n / (f - n);
  5621. 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);
  5622. };
  5623. /**
  5624. * 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.
  5625. */
  5626. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5627. if (rightHanded === void 0) { rightHanded = false; }
  5628. var rightHandedFactor = rightHanded ? -1 : 1;
  5629. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5630. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5631. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5632. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5633. var xScale = 2.0 / (leftTan + rightTan);
  5634. var yScale = 2.0 / (upTan + downTan);
  5635. result.m[0] = xScale;
  5636. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5637. result.m[5] = yScale;
  5638. result.m[6] = result.m[7] = 0.0;
  5639. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5640. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5641. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5642. result.m[10] = -zfar / (znear - zfar);
  5643. result.m[11] = 1.0 * rightHandedFactor;
  5644. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5645. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5646. // result.m[14] = (znear * zfar) / (znear - zfar);
  5647. result._markAsUpdated();
  5648. };
  5649. /**
  5650. * Returns the final transformation matrix : world * view * projection * viewport
  5651. */
  5652. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5653. var cw = viewport.width;
  5654. var ch = viewport.height;
  5655. var cx = viewport.x;
  5656. var cy = viewport.y;
  5657. 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);
  5658. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5659. };
  5660. /**
  5661. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5662. */
  5663. Matrix.GetAsMatrix2x2 = function (matrix) {
  5664. return new Float32Array([
  5665. matrix.m[0], matrix.m[1],
  5666. matrix.m[4], matrix.m[5]
  5667. ]);
  5668. };
  5669. /**
  5670. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5671. */
  5672. Matrix.GetAsMatrix3x3 = function (matrix) {
  5673. return new Float32Array([
  5674. matrix.m[0], matrix.m[1], matrix.m[2],
  5675. matrix.m[4], matrix.m[5], matrix.m[6],
  5676. matrix.m[8], matrix.m[9], matrix.m[10]
  5677. ]);
  5678. };
  5679. /**
  5680. * Compute the transpose of the passed Matrix.
  5681. * Returns a new Matrix.
  5682. */
  5683. Matrix.Transpose = function (matrix) {
  5684. var result = new Matrix();
  5685. Matrix.TransposeToRef(matrix, result);
  5686. return result;
  5687. };
  5688. /**
  5689. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5690. */
  5691. Matrix.TransposeToRef = function (matrix, result) {
  5692. result.m[0] = matrix.m[0];
  5693. result.m[1] = matrix.m[4];
  5694. result.m[2] = matrix.m[8];
  5695. result.m[3] = matrix.m[12];
  5696. result.m[4] = matrix.m[1];
  5697. result.m[5] = matrix.m[5];
  5698. result.m[6] = matrix.m[9];
  5699. result.m[7] = matrix.m[13];
  5700. result.m[8] = matrix.m[2];
  5701. result.m[9] = matrix.m[6];
  5702. result.m[10] = matrix.m[10];
  5703. result.m[11] = matrix.m[14];
  5704. result.m[12] = matrix.m[3];
  5705. result.m[13] = matrix.m[7];
  5706. result.m[14] = matrix.m[11];
  5707. result.m[15] = matrix.m[15];
  5708. };
  5709. /**
  5710. * Returns a new Matrix as the reflection matrix across the passed plane.
  5711. */
  5712. Matrix.Reflection = function (plane) {
  5713. var matrix = new Matrix();
  5714. Matrix.ReflectionToRef(plane, matrix);
  5715. return matrix;
  5716. };
  5717. /**
  5718. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5719. */
  5720. Matrix.ReflectionToRef = function (plane, result) {
  5721. plane.normalize();
  5722. var x = plane.normal.x;
  5723. var y = plane.normal.y;
  5724. var z = plane.normal.z;
  5725. var temp = -2 * x;
  5726. var temp2 = -2 * y;
  5727. var temp3 = -2 * z;
  5728. result.m[0] = (temp * x) + 1;
  5729. result.m[1] = temp2 * x;
  5730. result.m[2] = temp3 * x;
  5731. result.m[3] = 0.0;
  5732. result.m[4] = temp * y;
  5733. result.m[5] = (temp2 * y) + 1;
  5734. result.m[6] = temp3 * y;
  5735. result.m[7] = 0.0;
  5736. result.m[8] = temp * z;
  5737. result.m[9] = temp2 * z;
  5738. result.m[10] = (temp3 * z) + 1;
  5739. result.m[11] = 0.0;
  5740. result.m[12] = temp * plane.d;
  5741. result.m[13] = temp2 * plane.d;
  5742. result.m[14] = temp3 * plane.d;
  5743. result.m[15] = 1.0;
  5744. result._markAsUpdated();
  5745. };
  5746. /**
  5747. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5748. */
  5749. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5750. result.m[0] = xaxis.x;
  5751. result.m[1] = xaxis.y;
  5752. result.m[2] = xaxis.z;
  5753. result.m[3] = 0.0;
  5754. result.m[4] = yaxis.x;
  5755. result.m[5] = yaxis.y;
  5756. result.m[6] = yaxis.z;
  5757. result.m[7] = 0.0;
  5758. result.m[8] = zaxis.x;
  5759. result.m[9] = zaxis.y;
  5760. result.m[10] = zaxis.z;
  5761. result.m[11] = 0.0;
  5762. result.m[12] = 0.0;
  5763. result.m[13] = 0.0;
  5764. result.m[14] = 0.0;
  5765. result.m[15] = 1.0;
  5766. result._markAsUpdated();
  5767. };
  5768. /**
  5769. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5770. */
  5771. Matrix.FromQuaternionToRef = function (quat, result) {
  5772. var xx = quat.x * quat.x;
  5773. var yy = quat.y * quat.y;
  5774. var zz = quat.z * quat.z;
  5775. var xy = quat.x * quat.y;
  5776. var zw = quat.z * quat.w;
  5777. var zx = quat.z * quat.x;
  5778. var yw = quat.y * quat.w;
  5779. var yz = quat.y * quat.z;
  5780. var xw = quat.x * quat.w;
  5781. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5782. result.m[1] = 2.0 * (xy + zw);
  5783. result.m[2] = 2.0 * (zx - yw);
  5784. result.m[3] = 0.0;
  5785. result.m[4] = 2.0 * (xy - zw);
  5786. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5787. result.m[6] = 2.0 * (yz + xw);
  5788. result.m[7] = 0.0;
  5789. result.m[8] = 2.0 * (zx + yw);
  5790. result.m[9] = 2.0 * (yz - xw);
  5791. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5792. result.m[11] = 0.0;
  5793. result.m[12] = 0.0;
  5794. result.m[13] = 0.0;
  5795. result.m[14] = 0.0;
  5796. result.m[15] = 1.0;
  5797. result._markAsUpdated();
  5798. };
  5799. Matrix._tempQuaternion = new Quaternion();
  5800. Matrix._xAxis = Vector3.Zero();
  5801. Matrix._yAxis = Vector3.Zero();
  5802. Matrix._zAxis = Vector3.Zero();
  5803. Matrix._updateFlagSeed = 0;
  5804. Matrix._identityReadOnly = Matrix.Identity();
  5805. return Matrix;
  5806. }());
  5807. BABYLON.Matrix = Matrix;
  5808. var Plane = /** @class */ (function () {
  5809. /**
  5810. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5811. */
  5812. function Plane(a, b, c, d) {
  5813. this.normal = new Vector3(a, b, c);
  5814. this.d = d;
  5815. }
  5816. /**
  5817. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5818. */
  5819. Plane.prototype.asArray = function () {
  5820. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5821. };
  5822. // Methods
  5823. /**
  5824. * Returns a new plane copied from the current Plane.
  5825. */
  5826. Plane.prototype.clone = function () {
  5827. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5828. };
  5829. /**
  5830. * Returns the string "Plane".
  5831. */
  5832. Plane.prototype.getClassName = function () {
  5833. return "Plane";
  5834. };
  5835. /**
  5836. * Returns the Plane hash code.
  5837. */
  5838. Plane.prototype.getHashCode = function () {
  5839. var hash = this.normal.getHashCode();
  5840. hash = (hash * 397) ^ (this.d || 0);
  5841. return hash;
  5842. };
  5843. /**
  5844. * Normalize the current Plane in place.
  5845. * Returns the updated Plane.
  5846. */
  5847. Plane.prototype.normalize = function () {
  5848. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5849. var magnitude = 0.0;
  5850. if (norm !== 0) {
  5851. magnitude = 1.0 / norm;
  5852. }
  5853. this.normal.x *= magnitude;
  5854. this.normal.y *= magnitude;
  5855. this.normal.z *= magnitude;
  5856. this.d *= magnitude;
  5857. return this;
  5858. };
  5859. /**
  5860. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5861. */
  5862. Plane.prototype.transform = function (transformation) {
  5863. var transposedMatrix = Matrix.Transpose(transformation);
  5864. var x = this.normal.x;
  5865. var y = this.normal.y;
  5866. var z = this.normal.z;
  5867. var d = this.d;
  5868. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5869. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5870. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5871. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5872. return new Plane(normalX, normalY, normalZ, finalD);
  5873. };
  5874. /**
  5875. * Returns the dot product (float) of the point coordinates and the plane normal.
  5876. */
  5877. Plane.prototype.dotCoordinate = function (point) {
  5878. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5879. };
  5880. /**
  5881. * Updates the current Plane from the plane defined by the three passed points.
  5882. * Returns the updated Plane.
  5883. */
  5884. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5885. var x1 = point2.x - point1.x;
  5886. var y1 = point2.y - point1.y;
  5887. var z1 = point2.z - point1.z;
  5888. var x2 = point3.x - point1.x;
  5889. var y2 = point3.y - point1.y;
  5890. var z2 = point3.z - point1.z;
  5891. var yz = (y1 * z2) - (z1 * y2);
  5892. var xz = (z1 * x2) - (x1 * z2);
  5893. var xy = (x1 * y2) - (y1 * x2);
  5894. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5895. var invPyth;
  5896. if (pyth !== 0) {
  5897. invPyth = 1.0 / pyth;
  5898. }
  5899. else {
  5900. invPyth = 0.0;
  5901. }
  5902. this.normal.x = yz * invPyth;
  5903. this.normal.y = xz * invPyth;
  5904. this.normal.z = xy * invPyth;
  5905. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5906. return this;
  5907. };
  5908. /**
  5909. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5910. */
  5911. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5912. var dot = Vector3.Dot(this.normal, direction);
  5913. return (dot <= epsilon);
  5914. };
  5915. /**
  5916. * Returns the signed distance (float) from the passed point to the Plane.
  5917. */
  5918. Plane.prototype.signedDistanceTo = function (point) {
  5919. return Vector3.Dot(point, this.normal) + this.d;
  5920. };
  5921. // Statics
  5922. /**
  5923. * Returns a new Plane from the passed array.
  5924. */
  5925. Plane.FromArray = function (array) {
  5926. return new Plane(array[0], array[1], array[2], array[3]);
  5927. };
  5928. /**
  5929. * Returns a new Plane defined by the three passed points.
  5930. */
  5931. Plane.FromPoints = function (point1, point2, point3) {
  5932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5933. result.copyFromPoints(point1, point2, point3);
  5934. return result;
  5935. };
  5936. /**
  5937. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5938. * Note : the vector "normal" is updated because normalized.
  5939. */
  5940. Plane.FromPositionAndNormal = function (origin, normal) {
  5941. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5942. normal.normalize();
  5943. result.normal = normal;
  5944. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5945. return result;
  5946. };
  5947. /**
  5948. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5949. */
  5950. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5951. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5952. return Vector3.Dot(point, normal) + d;
  5953. };
  5954. return Plane;
  5955. }());
  5956. BABYLON.Plane = Plane;
  5957. var Viewport = /** @class */ (function () {
  5958. /**
  5959. * Creates a Viewport object located at (x, y) and sized (width, height).
  5960. */
  5961. function Viewport(x, y, width, height) {
  5962. this.x = x;
  5963. this.y = y;
  5964. this.width = width;
  5965. this.height = height;
  5966. }
  5967. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5968. if (renderWidthOrEngine.getRenderWidth) {
  5969. var engine = renderWidthOrEngine;
  5970. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5971. }
  5972. var renderWidth = renderWidthOrEngine;
  5973. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5974. };
  5975. /**
  5976. * Returns a new Viewport copied from the current one.
  5977. */
  5978. Viewport.prototype.clone = function () {
  5979. return new Viewport(this.x, this.y, this.width, this.height);
  5980. };
  5981. return Viewport;
  5982. }());
  5983. BABYLON.Viewport = Viewport;
  5984. var Frustum = /** @class */ (function () {
  5985. function Frustum() {
  5986. }
  5987. /**
  5988. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5989. */
  5990. Frustum.GetPlanes = function (transform) {
  5991. var frustumPlanes = [];
  5992. for (var index = 0; index < 6; index++) {
  5993. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5994. }
  5995. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5996. return frustumPlanes;
  5997. };
  5998. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5999. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6000. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6001. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6002. frustumPlane.d = transform.m[15] + transform.m[14];
  6003. frustumPlane.normalize();
  6004. };
  6005. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6006. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6007. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6008. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6009. frustumPlane.d = transform.m[15] - transform.m[14];
  6010. frustumPlane.normalize();
  6011. };
  6012. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6013. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6014. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6015. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6016. frustumPlane.d = transform.m[15] + transform.m[12];
  6017. frustumPlane.normalize();
  6018. };
  6019. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6020. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6021. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6022. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6023. frustumPlane.d = transform.m[15] - transform.m[12];
  6024. frustumPlane.normalize();
  6025. };
  6026. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6027. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6028. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6029. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6030. frustumPlane.d = transform.m[15] - transform.m[13];
  6031. frustumPlane.normalize();
  6032. };
  6033. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6034. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6035. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6036. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6037. frustumPlane.d = transform.m[15] + transform.m[13];
  6038. frustumPlane.normalize();
  6039. };
  6040. /**
  6041. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6042. */
  6043. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6044. // Near
  6045. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6046. // Far
  6047. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6048. // Left
  6049. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6050. // Right
  6051. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6052. // Top
  6053. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6054. // Bottom
  6055. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6056. };
  6057. return Frustum;
  6058. }());
  6059. BABYLON.Frustum = Frustum;
  6060. var Space;
  6061. (function (Space) {
  6062. Space[Space["LOCAL"] = 0] = "LOCAL";
  6063. Space[Space["WORLD"] = 1] = "WORLD";
  6064. Space[Space["BONE"] = 2] = "BONE";
  6065. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6066. var Axis = /** @class */ (function () {
  6067. function Axis() {
  6068. }
  6069. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6070. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6071. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6072. return Axis;
  6073. }());
  6074. BABYLON.Axis = Axis;
  6075. ;
  6076. var BezierCurve = /** @class */ (function () {
  6077. function BezierCurve() {
  6078. }
  6079. /**
  6080. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6081. */
  6082. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6083. // Extract X (which is equal to time here)
  6084. var f0 = 1 - 3 * x2 + 3 * x1;
  6085. var f1 = 3 * x2 - 6 * x1;
  6086. var f2 = 3 * x1;
  6087. var refinedT = t;
  6088. for (var i = 0; i < 5; i++) {
  6089. var refinedT2 = refinedT * refinedT;
  6090. var refinedT3 = refinedT2 * refinedT;
  6091. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6092. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6093. refinedT -= (x - t) * slope;
  6094. refinedT = Math.min(1, Math.max(0, refinedT));
  6095. }
  6096. // Resolve cubic bezier for the given x
  6097. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6098. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6099. Math.pow(refinedT, 3);
  6100. };
  6101. return BezierCurve;
  6102. }());
  6103. BABYLON.BezierCurve = BezierCurve;
  6104. var Orientation;
  6105. (function (Orientation) {
  6106. Orientation[Orientation["CW"] = 0] = "CW";
  6107. Orientation[Orientation["CCW"] = 1] = "CCW";
  6108. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6109. var Angle = /** @class */ (function () {
  6110. /**
  6111. * Creates an Angle object of "radians" radians (float).
  6112. */
  6113. function Angle(radians) {
  6114. var _this = this;
  6115. /**
  6116. * Returns the Angle value in degrees (float).
  6117. */
  6118. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6119. /**
  6120. * Returns the Angle value in radians (float).
  6121. */
  6122. this.radians = function () { return _this._radians; };
  6123. this._radians = radians;
  6124. if (this._radians < 0.0)
  6125. this._radians += (2.0 * Math.PI);
  6126. }
  6127. /**
  6128. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6129. */
  6130. Angle.BetweenTwoPoints = function (a, b) {
  6131. var delta = b.subtract(a);
  6132. var theta = Math.atan2(delta.y, delta.x);
  6133. return new Angle(theta);
  6134. };
  6135. /**
  6136. * Returns a new Angle object from the passed float in radians.
  6137. */
  6138. Angle.FromRadians = function (radians) {
  6139. return new Angle(radians);
  6140. };
  6141. /**
  6142. * Returns a new Angle object from the passed float in degrees.
  6143. */
  6144. Angle.FromDegrees = function (degrees) {
  6145. return new Angle(degrees * Math.PI / 180.0);
  6146. };
  6147. return Angle;
  6148. }());
  6149. BABYLON.Angle = Angle;
  6150. var Arc2 = /** @class */ (function () {
  6151. /**
  6152. * Creates an Arc object from the three passed points : start, middle and end.
  6153. */
  6154. function Arc2(startPoint, midPoint, endPoint) {
  6155. this.startPoint = startPoint;
  6156. this.midPoint = midPoint;
  6157. this.endPoint = endPoint;
  6158. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6159. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6160. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6161. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6162. 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);
  6163. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6164. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6165. var a1 = this.startAngle.degrees();
  6166. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6167. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6168. // angles correction
  6169. if (a2 - a1 > +180.0)
  6170. a2 -= 360.0;
  6171. if (a2 - a1 < -180.0)
  6172. a2 += 360.0;
  6173. if (a3 - a2 > +180.0)
  6174. a3 -= 360.0;
  6175. if (a3 - a2 < -180.0)
  6176. a3 += 360.0;
  6177. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6178. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6179. }
  6180. return Arc2;
  6181. }());
  6182. BABYLON.Arc2 = Arc2;
  6183. var Path2 = /** @class */ (function () {
  6184. /**
  6185. * Creates a Path2 object from the starting 2D coordinates x and y.
  6186. */
  6187. function Path2(x, y) {
  6188. this._points = new Array();
  6189. this._length = 0.0;
  6190. this.closed = false;
  6191. this._points.push(new Vector2(x, y));
  6192. }
  6193. /**
  6194. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6195. * Returns the updated Path2.
  6196. */
  6197. Path2.prototype.addLineTo = function (x, y) {
  6198. if (this.closed) {
  6199. return this;
  6200. }
  6201. var newPoint = new Vector2(x, y);
  6202. var previousPoint = this._points[this._points.length - 1];
  6203. this._points.push(newPoint);
  6204. this._length += newPoint.subtract(previousPoint).length();
  6205. return this;
  6206. };
  6207. /**
  6208. * 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.
  6209. * Returns the updated Path2.
  6210. */
  6211. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6212. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6213. if (this.closed) {
  6214. return this;
  6215. }
  6216. var startPoint = this._points[this._points.length - 1];
  6217. var midPoint = new Vector2(midX, midY);
  6218. var endPoint = new Vector2(endX, endY);
  6219. var arc = new Arc2(startPoint, midPoint, endPoint);
  6220. var increment = arc.angle.radians() / numberOfSegments;
  6221. if (arc.orientation === Orientation.CW)
  6222. increment *= -1;
  6223. var currentAngle = arc.startAngle.radians() + increment;
  6224. for (var i = 0; i < numberOfSegments; i++) {
  6225. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6226. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6227. this.addLineTo(x, y);
  6228. currentAngle += increment;
  6229. }
  6230. return this;
  6231. };
  6232. /**
  6233. * Closes the Path2.
  6234. * Returns the Path2.
  6235. */
  6236. Path2.prototype.close = function () {
  6237. this.closed = true;
  6238. return this;
  6239. };
  6240. /**
  6241. * Returns the Path2 total length (float).
  6242. */
  6243. Path2.prototype.length = function () {
  6244. var result = this._length;
  6245. if (!this.closed) {
  6246. var lastPoint = this._points[this._points.length - 1];
  6247. var firstPoint = this._points[0];
  6248. result += (firstPoint.subtract(lastPoint).length());
  6249. }
  6250. return result;
  6251. };
  6252. /**
  6253. * Returns the Path2 internal array of points.
  6254. */
  6255. Path2.prototype.getPoints = function () {
  6256. return this._points;
  6257. };
  6258. /**
  6259. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6260. */
  6261. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6262. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6263. return Vector2.Zero();
  6264. }
  6265. var lengthPosition = normalizedLengthPosition * this.length();
  6266. var previousOffset = 0;
  6267. for (var i = 0; i < this._points.length; i++) {
  6268. var j = (i + 1) % this._points.length;
  6269. var a = this._points[i];
  6270. var b = this._points[j];
  6271. var bToA = b.subtract(a);
  6272. var nextOffset = (bToA.length() + previousOffset);
  6273. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6274. var dir = bToA.normalize();
  6275. var localOffset = lengthPosition - previousOffset;
  6276. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6277. }
  6278. previousOffset = nextOffset;
  6279. }
  6280. return Vector2.Zero();
  6281. };
  6282. /**
  6283. * Returns a new Path2 starting at the coordinates (x, y).
  6284. */
  6285. Path2.StartingAt = function (x, y) {
  6286. return new Path2(x, y);
  6287. };
  6288. return Path2;
  6289. }());
  6290. BABYLON.Path2 = Path2;
  6291. var Path3D = /** @class */ (function () {
  6292. /**
  6293. * new Path3D(path, normal, raw)
  6294. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6295. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6296. * path : an array of Vector3, the curve axis of the Path3D
  6297. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6298. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6299. */
  6300. function Path3D(path, firstNormal, raw) {
  6301. if (firstNormal === void 0) { firstNormal = null; }
  6302. this.path = path;
  6303. this._curve = new Array();
  6304. this._distances = new Array();
  6305. this._tangents = new Array();
  6306. this._normals = new Array();
  6307. this._binormals = new Array();
  6308. for (var p = 0; p < path.length; p++) {
  6309. this._curve[p] = path[p].clone(); // hard copy
  6310. }
  6311. this._raw = raw || false;
  6312. this._compute(firstNormal);
  6313. }
  6314. /**
  6315. * Returns the Path3D array of successive Vector3 designing its curve.
  6316. */
  6317. Path3D.prototype.getCurve = function () {
  6318. return this._curve;
  6319. };
  6320. /**
  6321. * Returns an array populated with tangent vectors on each Path3D curve point.
  6322. */
  6323. Path3D.prototype.getTangents = function () {
  6324. return this._tangents;
  6325. };
  6326. /**
  6327. * Returns an array populated with normal vectors on each Path3D curve point.
  6328. */
  6329. Path3D.prototype.getNormals = function () {
  6330. return this._normals;
  6331. };
  6332. /**
  6333. * Returns an array populated with binormal vectors on each Path3D curve point.
  6334. */
  6335. Path3D.prototype.getBinormals = function () {
  6336. return this._binormals;
  6337. };
  6338. /**
  6339. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6340. */
  6341. Path3D.prototype.getDistances = function () {
  6342. return this._distances;
  6343. };
  6344. /**
  6345. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6346. * Returns the same object updated.
  6347. */
  6348. Path3D.prototype.update = function (path, firstNormal) {
  6349. if (firstNormal === void 0) { firstNormal = null; }
  6350. for (var p = 0; p < path.length; p++) {
  6351. this._curve[p].x = path[p].x;
  6352. this._curve[p].y = path[p].y;
  6353. this._curve[p].z = path[p].z;
  6354. }
  6355. this._compute(firstNormal);
  6356. return this;
  6357. };
  6358. // private function compute() : computes tangents, normals and binormals
  6359. Path3D.prototype._compute = function (firstNormal) {
  6360. var l = this._curve.length;
  6361. // first and last tangents
  6362. this._tangents[0] = this._getFirstNonNullVector(0);
  6363. if (!this._raw) {
  6364. this._tangents[0].normalize();
  6365. }
  6366. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6367. if (!this._raw) {
  6368. this._tangents[l - 1].normalize();
  6369. }
  6370. // normals and binormals at first point : arbitrary vector with _normalVector()
  6371. var tg0 = this._tangents[0];
  6372. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6373. this._normals[0] = pp0;
  6374. if (!this._raw) {
  6375. this._normals[0].normalize();
  6376. }
  6377. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6378. if (!this._raw) {
  6379. this._binormals[0].normalize();
  6380. }
  6381. this._distances[0] = 0.0;
  6382. // normals and binormals : next points
  6383. var prev; // previous vector (segment)
  6384. var cur; // current vector (segment)
  6385. var curTang; // current tangent
  6386. // previous normal
  6387. var prevBinor; // previous binormal
  6388. for (var i = 1; i < l; i++) {
  6389. // tangents
  6390. prev = this._getLastNonNullVector(i);
  6391. if (i < l - 1) {
  6392. cur = this._getFirstNonNullVector(i);
  6393. this._tangents[i] = prev.add(cur);
  6394. this._tangents[i].normalize();
  6395. }
  6396. this._distances[i] = this._distances[i - 1] + prev.length();
  6397. // normals and binormals
  6398. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6399. curTang = this._tangents[i];
  6400. prevBinor = this._binormals[i - 1];
  6401. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6402. if (!this._raw) {
  6403. this._normals[i].normalize();
  6404. }
  6405. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6406. if (!this._raw) {
  6407. this._binormals[i].normalize();
  6408. }
  6409. }
  6410. };
  6411. // private function getFirstNonNullVector(index)
  6412. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6413. Path3D.prototype._getFirstNonNullVector = function (index) {
  6414. var i = 1;
  6415. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6416. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6417. i++;
  6418. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6419. }
  6420. return nNVector;
  6421. };
  6422. // private function getLastNonNullVector(index)
  6423. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6424. Path3D.prototype._getLastNonNullVector = function (index) {
  6425. var i = 1;
  6426. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6427. while (nLVector.length() === 0 && index > i + 1) {
  6428. i++;
  6429. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6430. }
  6431. return nLVector;
  6432. };
  6433. // private function normalVector(v0, vt, va) :
  6434. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6435. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6436. Path3D.prototype._normalVector = function (v0, vt, va) {
  6437. var normal0;
  6438. var tgl = vt.length();
  6439. if (tgl === 0.0) {
  6440. tgl = 1.0;
  6441. }
  6442. if (va === undefined || va === null) {
  6443. var point;
  6444. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6445. point = new Vector3(0.0, -1.0, 0.0);
  6446. }
  6447. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6448. point = new Vector3(1.0, 0.0, 0.0);
  6449. }
  6450. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6451. point = new Vector3(0.0, 0.0, 1.0);
  6452. }
  6453. else {
  6454. point = Vector3.Zero();
  6455. }
  6456. normal0 = Vector3.Cross(vt, point);
  6457. }
  6458. else {
  6459. normal0 = Vector3.Cross(vt, va);
  6460. Vector3.CrossToRef(normal0, vt, normal0);
  6461. }
  6462. normal0.normalize();
  6463. return normal0;
  6464. };
  6465. return Path3D;
  6466. }());
  6467. BABYLON.Path3D = Path3D;
  6468. var Curve3 = /** @class */ (function () {
  6469. /**
  6470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6471. * A Curve3 is designed from a series of successive Vector3.
  6472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6473. */
  6474. function Curve3(points) {
  6475. this._length = 0.0;
  6476. this._points = points;
  6477. this._length = this._computeLength(points);
  6478. }
  6479. /**
  6480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6482. * @param v1 (Vector3) the control point
  6483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6484. * @param nbPoints (integer) the wanted number of points in the curve
  6485. */
  6486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6488. var bez = new Array();
  6489. var equation = function (t, val0, val1, val2) {
  6490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6491. return res;
  6492. };
  6493. for (var i = 0; i <= nbPoints; i++) {
  6494. 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)));
  6495. }
  6496. return new Curve3(bez);
  6497. };
  6498. /**
  6499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6501. * @param v1 (Vector3) the first control point
  6502. * @param v2 (Vector3) the second control point
  6503. * @param v3 (Vector3) the end point of the Cubic Bezier
  6504. * @param nbPoints (integer) the wanted number of points in the curve
  6505. */
  6506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6508. var bez = new Array();
  6509. var equation = function (t, val0, val1, val2, val3) {
  6510. 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;
  6511. return res;
  6512. };
  6513. for (var i = 0; i <= nbPoints; i++) {
  6514. 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)));
  6515. }
  6516. return new Curve3(bez);
  6517. };
  6518. /**
  6519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6520. * @param p1 (Vector3) the origin point of the Hermite Spline
  6521. * @param t1 (Vector3) the tangent vector at the origin point
  6522. * @param p2 (Vector3) the end point of the Hermite Spline
  6523. * @param t2 (Vector3) the tangent vector at the end point
  6524. * @param nbPoints (integer) the wanted number of points in the curve
  6525. */
  6526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6527. var hermite = new Array();
  6528. var step = 1.0 / nbPoints;
  6529. for (var i = 0; i <= nbPoints; i++) {
  6530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6531. }
  6532. return new Curve3(hermite);
  6533. };
  6534. /**
  6535. * Returns a Curve3 object along a CatmullRom Spline curve :
  6536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6538. */
  6539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6540. var totalPoints = new Array();
  6541. totalPoints.push(points[0].clone());
  6542. Array.prototype.push.apply(totalPoints, points);
  6543. totalPoints.push(points[points.length - 1].clone());
  6544. var catmullRom = new Array();
  6545. var step = 1.0 / nbPoints;
  6546. var amount = 0.0;
  6547. for (var i = 0; i < totalPoints.length - 3; i++) {
  6548. amount = 0;
  6549. for (var c = 0; c < nbPoints; c++) {
  6550. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6551. amount += step;
  6552. }
  6553. }
  6554. i--;
  6555. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6556. return new Curve3(catmullRom);
  6557. };
  6558. /**
  6559. * Returns the Curve3 stored array of successive Vector3
  6560. */
  6561. Curve3.prototype.getPoints = function () {
  6562. return this._points;
  6563. };
  6564. /**
  6565. * Returns the computed length (float) of the curve.
  6566. */
  6567. Curve3.prototype.length = function () {
  6568. return this._length;
  6569. };
  6570. /**
  6571. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6572. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6573. * curveA and curveB keep unchanged.
  6574. */
  6575. Curve3.prototype.continue = function (curve) {
  6576. var lastPoint = this._points[this._points.length - 1];
  6577. var continuedPoints = this._points.slice();
  6578. var curvePoints = curve.getPoints();
  6579. for (var i = 1; i < curvePoints.length; i++) {
  6580. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6581. }
  6582. var continuedCurve = new Curve3(continuedPoints);
  6583. return continuedCurve;
  6584. };
  6585. Curve3.prototype._computeLength = function (path) {
  6586. var l = 0;
  6587. for (var i = 1; i < path.length; i++) {
  6588. l += (path[i].subtract(path[i - 1])).length();
  6589. }
  6590. return l;
  6591. };
  6592. return Curve3;
  6593. }());
  6594. BABYLON.Curve3 = Curve3;
  6595. // Vertex formats
  6596. var PositionNormalVertex = /** @class */ (function () {
  6597. function PositionNormalVertex(position, normal) {
  6598. if (position === void 0) { position = Vector3.Zero(); }
  6599. if (normal === void 0) { normal = Vector3.Up(); }
  6600. this.position = position;
  6601. this.normal = normal;
  6602. }
  6603. PositionNormalVertex.prototype.clone = function () {
  6604. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6605. };
  6606. return PositionNormalVertex;
  6607. }());
  6608. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6609. var PositionNormalTextureVertex = /** @class */ (function () {
  6610. function PositionNormalTextureVertex(position, normal, uv) {
  6611. if (position === void 0) { position = Vector3.Zero(); }
  6612. if (normal === void 0) { normal = Vector3.Up(); }
  6613. if (uv === void 0) { uv = Vector2.Zero(); }
  6614. this.position = position;
  6615. this.normal = normal;
  6616. this.uv = uv;
  6617. }
  6618. PositionNormalTextureVertex.prototype.clone = function () {
  6619. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6620. };
  6621. return PositionNormalTextureVertex;
  6622. }());
  6623. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6624. // Temporary pre-allocated objects for engine internal use
  6625. // usage in any internal function :
  6626. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6627. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6628. var Tmp = /** @class */ (function () {
  6629. function Tmp() {
  6630. }
  6631. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6632. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6633. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6634. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6635. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6636. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6637. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6638. Matrix.Zero(), Matrix.Zero(),
  6639. Matrix.Zero(), Matrix.Zero(),
  6640. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6641. return Tmp;
  6642. }());
  6643. BABYLON.Tmp = Tmp;
  6644. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6645. var MathTmp = /** @class */ (function () {
  6646. function MathTmp() {
  6647. }
  6648. MathTmp.Vector3 = [Vector3.Zero()];
  6649. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6650. MathTmp.Quaternion = [Quaternion.Zero()];
  6651. return MathTmp;
  6652. }());
  6653. })(BABYLON || (BABYLON = {}));
  6654. //# sourceMappingURL=babylon.math.js.map
  6655. var BABYLON;
  6656. (function (BABYLON) {
  6657. var Scalar = /** @class */ (function () {
  6658. function Scalar() {
  6659. }
  6660. /**
  6661. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6662. */
  6663. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6664. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6665. var num = a - b;
  6666. return -epsilon <= num && num <= epsilon;
  6667. };
  6668. /**
  6669. * Returns a string : the upper case translation of the number i to hexadecimal.
  6670. */
  6671. Scalar.ToHex = function (i) {
  6672. var str = i.toString(16);
  6673. if (i <= 15) {
  6674. return ("0" + str).toUpperCase();
  6675. }
  6676. return str.toUpperCase();
  6677. };
  6678. /**
  6679. * Returns -1 if value is negative and +1 is value is positive.
  6680. * Returns the value itself if it's equal to zero.
  6681. */
  6682. Scalar.Sign = function (value) {
  6683. value = +value; // convert to a number
  6684. if (value === 0 || isNaN(value))
  6685. return value;
  6686. return value > 0 ? 1 : -1;
  6687. };
  6688. /**
  6689. * Returns the value itself if it's between min and max.
  6690. * Returns min if the value is lower than min.
  6691. * Returns max if the value is greater than max.
  6692. */
  6693. Scalar.Clamp = function (value, min, max) {
  6694. if (min === void 0) { min = 0; }
  6695. if (max === void 0) { max = 1; }
  6696. return Math.min(max, Math.max(min, value));
  6697. };
  6698. /**
  6699. * Returns the log2 of value.
  6700. */
  6701. Scalar.Log2 = function (value) {
  6702. return Math.log(value) * Math.LOG2E;
  6703. };
  6704. /**
  6705. * Loops the value, so that it is never larger than length and never smaller than 0.
  6706. *
  6707. * This is similar to the modulo operator but it works with floating point numbers.
  6708. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6709. * With t = 5 and length = 2.5, the result would be 0.0.
  6710. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6711. */
  6712. Scalar.Repeat = function (value, length) {
  6713. return value - Math.floor(value / length) * length;
  6714. };
  6715. /**
  6716. * Normalize the value between 0.0 and 1.0 using min and max values
  6717. */
  6718. Scalar.Normalize = function (value, min, max) {
  6719. return (value - min) / (max - min);
  6720. };
  6721. /**
  6722. * Denormalize the value from 0.0 and 1.0 using min and max values
  6723. */
  6724. Scalar.Denormalize = function (normalized, min, max) {
  6725. return (normalized * (max - min) + min);
  6726. };
  6727. /**
  6728. * Calculates the shortest difference between two given angles given in degrees.
  6729. */
  6730. Scalar.DeltaAngle = function (current, target) {
  6731. var num = Scalar.Repeat(target - current, 360.0);
  6732. if (num > 180.0) {
  6733. num -= 360.0;
  6734. }
  6735. return num;
  6736. };
  6737. /**
  6738. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6739. *
  6740. * The returned value will move back and forth between 0 and length
  6741. */
  6742. Scalar.PingPong = function (tx, length) {
  6743. var t = Scalar.Repeat(tx, length * 2.0);
  6744. return length - Math.abs(t - length);
  6745. };
  6746. /**
  6747. * Interpolates between min and max with smoothing at the limits.
  6748. *
  6749. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6750. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6751. */
  6752. Scalar.SmoothStep = function (from, to, tx) {
  6753. var t = Scalar.Clamp(tx);
  6754. t = -2.0 * t * t * t + 3.0 * t * t;
  6755. return to * t + from * (1.0 - t);
  6756. };
  6757. /**
  6758. * Moves a value current towards target.
  6759. *
  6760. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6761. * Negative values of maxDelta pushes the value away from target.
  6762. */
  6763. Scalar.MoveTowards = function (current, target, maxDelta) {
  6764. var result = 0;
  6765. if (Math.abs(target - current) <= maxDelta) {
  6766. result = target;
  6767. }
  6768. else {
  6769. result = current + Scalar.Sign(target - current) * maxDelta;
  6770. }
  6771. return result;
  6772. };
  6773. /**
  6774. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6775. *
  6776. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6777. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6778. */
  6779. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6780. var num = Scalar.DeltaAngle(current, target);
  6781. var result = 0;
  6782. if (-maxDelta < num && num < maxDelta) {
  6783. result = target;
  6784. }
  6785. else {
  6786. target = current + num;
  6787. result = Scalar.MoveTowards(current, target, maxDelta);
  6788. }
  6789. return result;
  6790. };
  6791. /**
  6792. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6793. */
  6794. Scalar.Lerp = function (start, end, amount) {
  6795. return start + ((end - start) * amount);
  6796. };
  6797. /**
  6798. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6799. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6800. */
  6801. Scalar.LerpAngle = function (start, end, amount) {
  6802. var num = Scalar.Repeat(end - start, 360.0);
  6803. if (num > 180.0) {
  6804. num -= 360.0;
  6805. }
  6806. return start + num * Scalar.Clamp(amount);
  6807. };
  6808. /**
  6809. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6810. */
  6811. Scalar.InverseLerp = function (a, b, value) {
  6812. var result = 0;
  6813. if (a != b) {
  6814. result = Scalar.Clamp((value - a) / (b - a));
  6815. }
  6816. else {
  6817. result = 0.0;
  6818. }
  6819. return result;
  6820. };
  6821. /**
  6822. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6823. */
  6824. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6825. var squared = amount * amount;
  6826. var cubed = amount * squared;
  6827. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6828. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6829. var part3 = (cubed - (2.0 * squared)) + amount;
  6830. var part4 = cubed - squared;
  6831. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6832. };
  6833. /**
  6834. * Returns a random float number between and min and max values
  6835. */
  6836. Scalar.RandomRange = function (min, max) {
  6837. if (min === max)
  6838. return min;
  6839. return ((Math.random() * (max - min)) + min);
  6840. };
  6841. /**
  6842. * This function returns percentage of a number in a given range.
  6843. *
  6844. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6845. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6846. */
  6847. Scalar.RangeToPercent = function (number, min, max) {
  6848. return ((number - min) / (max - min));
  6849. };
  6850. /**
  6851. * This function returns number that corresponds to the percentage in a given range.
  6852. *
  6853. * PercentToRange(0.34,0,100) will return 34.
  6854. */
  6855. Scalar.PercentToRange = function (percent, min, max) {
  6856. return ((max - min) * percent + min);
  6857. };
  6858. /**
  6859. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6860. * @param angle The angle to normalize in radian.
  6861. * @return The converted angle.
  6862. */
  6863. Scalar.NormalizeRadians = function (angle) {
  6864. // More precise but slower version kept for reference.
  6865. // angle = angle % Tools.TwoPi;
  6866. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6867. //if (angle > Math.PI) {
  6868. // angle -= Tools.TwoPi;
  6869. //}
  6870. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6871. return angle;
  6872. };
  6873. /**
  6874. * Two pi constants convenient for computation.
  6875. */
  6876. Scalar.TwoPi = Math.PI * 2;
  6877. return Scalar;
  6878. }());
  6879. BABYLON.Scalar = Scalar;
  6880. })(BABYLON || (BABYLON = {}));
  6881. //# sourceMappingURL=babylon.math.scalar.js.map
  6882. //# sourceMappingURL=babylon.mixins.js.map
  6883. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6884. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6885. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6886. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6887. //# sourceMappingURL=babylon.webgl2.js.map
  6888. var BABYLON;
  6889. (function (BABYLON) {
  6890. var __decoratorInitialStore = {};
  6891. var __mergedStore = {};
  6892. var _copySource = function (creationFunction, source, instanciate) {
  6893. var destination = creationFunction();
  6894. // Tags
  6895. if (BABYLON.Tags) {
  6896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6897. }
  6898. var classStore = getMergedStore(destination);
  6899. // Properties
  6900. for (var property in classStore) {
  6901. var propertyDescriptor = classStore[property];
  6902. var sourceProperty = source[property];
  6903. var propertyType = propertyDescriptor.type;
  6904. if (sourceProperty !== undefined && sourceProperty !== null) {
  6905. switch (propertyType) {
  6906. case 0: // Value
  6907. case 6:// Mesh reference
  6908. destination[property] = sourceProperty;
  6909. break;
  6910. case 1:// Texture
  6911. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6912. break;
  6913. case 2: // Color3
  6914. case 3: // FresnelParameters
  6915. case 4: // Vector2
  6916. case 5: // Vector3
  6917. case 7: // Color Curves
  6918. case 10:// Quaternion
  6919. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6920. break;
  6921. }
  6922. }
  6923. }
  6924. return destination;
  6925. };
  6926. function getDirectStore(target) {
  6927. var classKey = target.getClassName();
  6928. if (!__decoratorInitialStore[classKey]) {
  6929. __decoratorInitialStore[classKey] = {};
  6930. }
  6931. return __decoratorInitialStore[classKey];
  6932. }
  6933. /**
  6934. * Return the list of properties flagged as serializable
  6935. * @param target: host object
  6936. */
  6937. function getMergedStore(target) {
  6938. var classKey = target.getClassName();
  6939. if (__mergedStore[classKey]) {
  6940. return __mergedStore[classKey];
  6941. }
  6942. __mergedStore[classKey] = {};
  6943. var store = __mergedStore[classKey];
  6944. var currentTarget = target;
  6945. var currentKey = classKey;
  6946. while (currentKey) {
  6947. var initialStore = __decoratorInitialStore[currentKey];
  6948. for (var property in initialStore) {
  6949. store[property] = initialStore[property];
  6950. }
  6951. var parent_1 = void 0;
  6952. var done = false;
  6953. do {
  6954. parent_1 = Object.getPrototypeOf(currentTarget);
  6955. if (!parent_1.getClassName) {
  6956. done = true;
  6957. break;
  6958. }
  6959. if (parent_1.getClassName() !== currentKey) {
  6960. break;
  6961. }
  6962. currentTarget = parent_1;
  6963. } while (parent_1);
  6964. if (done) {
  6965. break;
  6966. }
  6967. currentKey = parent_1.getClassName();
  6968. currentTarget = parent_1;
  6969. }
  6970. return store;
  6971. }
  6972. function generateSerializableMember(type, sourceName) {
  6973. return function (target, propertyKey) {
  6974. var classStore = getDirectStore(target);
  6975. if (!classStore[propertyKey]) {
  6976. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6977. }
  6978. };
  6979. }
  6980. function generateExpandMember(setCallback, targetKey) {
  6981. if (targetKey === void 0) { targetKey = null; }
  6982. return function (target, propertyKey) {
  6983. var key = targetKey || ("_" + propertyKey);
  6984. Object.defineProperty(target, propertyKey, {
  6985. get: function () {
  6986. return this[key];
  6987. },
  6988. set: function (value) {
  6989. if (this[key] === value) {
  6990. return;
  6991. }
  6992. this[key] = value;
  6993. target[setCallback].apply(this);
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. };
  6999. }
  7000. function expandToProperty(callback, targetKey) {
  7001. if (targetKey === void 0) { targetKey = null; }
  7002. return generateExpandMember(callback, targetKey);
  7003. }
  7004. BABYLON.expandToProperty = expandToProperty;
  7005. function serialize(sourceName) {
  7006. return generateSerializableMember(0, sourceName); // value member
  7007. }
  7008. BABYLON.serialize = serialize;
  7009. function serializeAsTexture(sourceName) {
  7010. return generateSerializableMember(1, sourceName); // texture member
  7011. }
  7012. BABYLON.serializeAsTexture = serializeAsTexture;
  7013. function serializeAsColor3(sourceName) {
  7014. return generateSerializableMember(2, sourceName); // color3 member
  7015. }
  7016. BABYLON.serializeAsColor3 = serializeAsColor3;
  7017. function serializeAsFresnelParameters(sourceName) {
  7018. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7019. }
  7020. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7021. function serializeAsVector2(sourceName) {
  7022. return generateSerializableMember(4, sourceName); // vector2 member
  7023. }
  7024. BABYLON.serializeAsVector2 = serializeAsVector2;
  7025. function serializeAsVector3(sourceName) {
  7026. return generateSerializableMember(5, sourceName); // vector3 member
  7027. }
  7028. BABYLON.serializeAsVector3 = serializeAsVector3;
  7029. function serializeAsMeshReference(sourceName) {
  7030. return generateSerializableMember(6, sourceName); // mesh reference member
  7031. }
  7032. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7033. function serializeAsColorCurves(sourceName) {
  7034. return generateSerializableMember(7, sourceName); // color curves
  7035. }
  7036. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7037. function serializeAsColor4(sourceName) {
  7038. return generateSerializableMember(8, sourceName); // color 4
  7039. }
  7040. BABYLON.serializeAsColor4 = serializeAsColor4;
  7041. function serializeAsImageProcessingConfiguration(sourceName) {
  7042. return generateSerializableMember(9, sourceName); // image processing
  7043. }
  7044. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7045. function serializeAsQuaternion(sourceName) {
  7046. return generateSerializableMember(10, sourceName); // quaternion member
  7047. }
  7048. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7049. var SerializationHelper = /** @class */ (function () {
  7050. function SerializationHelper() {
  7051. }
  7052. SerializationHelper.Serialize = function (entity, serializationObject) {
  7053. if (!serializationObject) {
  7054. serializationObject = {};
  7055. }
  7056. // Tags
  7057. if (BABYLON.Tags) {
  7058. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7059. }
  7060. var serializedProperties = getMergedStore(entity);
  7061. // Properties
  7062. for (var property in serializedProperties) {
  7063. var propertyDescriptor = serializedProperties[property];
  7064. var targetPropertyName = propertyDescriptor.sourceName || property;
  7065. var propertyType = propertyDescriptor.type;
  7066. var sourceProperty = entity[property];
  7067. if (sourceProperty !== undefined && sourceProperty !== null) {
  7068. switch (propertyType) {
  7069. case 0:// Value
  7070. serializationObject[targetPropertyName] = sourceProperty;
  7071. break;
  7072. case 1:// Texture
  7073. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7074. break;
  7075. case 2:// Color3
  7076. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7077. break;
  7078. case 3:// FresnelParameters
  7079. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7080. break;
  7081. case 4:// Vector2
  7082. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7083. break;
  7084. case 5:// Vector3
  7085. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7086. break;
  7087. case 6:// Mesh reference
  7088. serializationObject[targetPropertyName] = sourceProperty.id;
  7089. break;
  7090. case 7:// Color Curves
  7091. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7092. break;
  7093. case 8:// Color 4
  7094. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7095. break;
  7096. case 9:// Image Processing
  7097. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7098. break;
  7099. }
  7100. }
  7101. }
  7102. return serializationObject;
  7103. };
  7104. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7105. if (rootUrl === void 0) { rootUrl = null; }
  7106. var destination = creationFunction();
  7107. if (!rootUrl) {
  7108. rootUrl = "";
  7109. }
  7110. // Tags
  7111. if (BABYLON.Tags) {
  7112. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7113. }
  7114. var classStore = getMergedStore(destination);
  7115. // Properties
  7116. for (var property in classStore) {
  7117. var propertyDescriptor = classStore[property];
  7118. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7119. var propertyType = propertyDescriptor.type;
  7120. if (sourceProperty !== undefined && sourceProperty !== null) {
  7121. var dest = destination;
  7122. switch (propertyType) {
  7123. case 0:// Value
  7124. dest[property] = sourceProperty;
  7125. break;
  7126. case 1:// Texture
  7127. if (scene) {
  7128. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7129. }
  7130. break;
  7131. case 2:// Color3
  7132. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7133. break;
  7134. case 3:// FresnelParameters
  7135. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7136. break;
  7137. case 4:// Vector2
  7138. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7139. break;
  7140. case 5:// Vector3
  7141. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7142. break;
  7143. case 6:// Mesh reference
  7144. if (scene) {
  7145. dest[property] = scene.getLastMeshByID(sourceProperty);
  7146. }
  7147. break;
  7148. case 7:// Color Curves
  7149. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7150. break;
  7151. case 8:// Color 4
  7152. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7153. break;
  7154. case 9:// Image Processing
  7155. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. return destination;
  7161. };
  7162. SerializationHelper.Clone = function (creationFunction, source) {
  7163. return _copySource(creationFunction, source, false);
  7164. };
  7165. SerializationHelper.Instanciate = function (creationFunction, source) {
  7166. return _copySource(creationFunction, source, true);
  7167. };
  7168. return SerializationHelper;
  7169. }());
  7170. BABYLON.SerializationHelper = SerializationHelper;
  7171. })(BABYLON || (BABYLON = {}));
  7172. //# sourceMappingURL=babylon.decorators.js.map
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. /**
  7176. * Wrapper class for promise with external resolve and reject.
  7177. */
  7178. var Deferred = /** @class */ (function () {
  7179. /**
  7180. * Constructor for this deferred object.
  7181. */
  7182. function Deferred() {
  7183. var _this = this;
  7184. this.promise = new Promise(function (resolve, reject) {
  7185. _this._resolve = resolve;
  7186. _this._reject = reject;
  7187. });
  7188. }
  7189. Object.defineProperty(Deferred.prototype, "resolve", {
  7190. /**
  7191. * The resolve method of the promise associated with this deferred object.
  7192. */
  7193. get: function () {
  7194. return this._resolve;
  7195. },
  7196. enumerable: true,
  7197. configurable: true
  7198. });
  7199. Object.defineProperty(Deferred.prototype, "reject", {
  7200. /**
  7201. * The reject method of the promise associated with this deferred object.
  7202. */
  7203. get: function () {
  7204. return this._reject;
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. return Deferred;
  7210. }());
  7211. BABYLON.Deferred = Deferred;
  7212. })(BABYLON || (BABYLON = {}));
  7213. //# sourceMappingURL=babylon.deferred.js.map
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. /**
  7217. * A class serves as a medium between the observable and its observers
  7218. */
  7219. var EventState = /** @class */ (function () {
  7220. /**
  7221. * Create a new EventState
  7222. * @param mask defines the mask associated with this state
  7223. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7224. * @param target defines the original target of the state
  7225. * @param currentTarget defines the current target of the state
  7226. */
  7227. function EventState(mask, skipNextObservers, target, currentTarget) {
  7228. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7229. this.initalize(mask, skipNextObservers, target, currentTarget);
  7230. }
  7231. /**
  7232. * Initialize the current event state
  7233. * @param mask defines the mask associated with this state
  7234. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7235. * @param target defines the original target of the state
  7236. * @param currentTarget defines the current target of the state
  7237. * @returns the current event state
  7238. */
  7239. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7240. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7241. this.mask = mask;
  7242. this.skipNextObservers = skipNextObservers;
  7243. this.target = target;
  7244. this.currentTarget = currentTarget;
  7245. return this;
  7246. };
  7247. return EventState;
  7248. }());
  7249. BABYLON.EventState = EventState;
  7250. /**
  7251. * Represent an Observer registered to a given Observable object.
  7252. */
  7253. var Observer = /** @class */ (function () {
  7254. /**
  7255. * Creates a new observer
  7256. * @param callback defines the callback to call when the observer is notified
  7257. * @param mask defines the mask of the observer (used to filter notifications)
  7258. * @param scope defines the current scope used to restore the JS context
  7259. */
  7260. function Observer(
  7261. /**
  7262. * Defines the callback to call when the observer is notified
  7263. */
  7264. callback,
  7265. /**
  7266. * Defines the mask of the observer (used to filter notifications)
  7267. */
  7268. mask,
  7269. /**
  7270. * Defines the current scope used to restore the JS context
  7271. */
  7272. scope) {
  7273. if (scope === void 0) { scope = null; }
  7274. this.callback = callback;
  7275. this.mask = mask;
  7276. this.scope = scope;
  7277. /** @ignore */
  7278. this._willBeUnregistered = false;
  7279. /**
  7280. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7281. */
  7282. this.unregisterOnNextCall = false;
  7283. }
  7284. return Observer;
  7285. }());
  7286. BABYLON.Observer = Observer;
  7287. /**
  7288. * Represent a list of observers registered to multiple Observables object.
  7289. */
  7290. var MultiObserver = /** @class */ (function () {
  7291. function MultiObserver() {
  7292. }
  7293. /**
  7294. * Release associated resources
  7295. */
  7296. MultiObserver.prototype.dispose = function () {
  7297. if (this._observers && this._observables) {
  7298. for (var index = 0; index < this._observers.length; index++) {
  7299. this._observables[index].remove(this._observers[index]);
  7300. }
  7301. }
  7302. this._observers = null;
  7303. this._observables = null;
  7304. };
  7305. /**
  7306. * Raise a callback when one of the observable will notify
  7307. * @param observables defines a list of observables to watch
  7308. * @param callback defines the callback to call on notification
  7309. * @param mask defines the mask used to filter notifications
  7310. * @param scope defines the current scope used to restore the JS context
  7311. * @returns the new MultiObserver
  7312. */
  7313. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7314. if (mask === void 0) { mask = -1; }
  7315. if (scope === void 0) { scope = null; }
  7316. var result = new MultiObserver();
  7317. result._observers = new Array();
  7318. result._observables = observables;
  7319. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7320. var observable = observables_1[_i];
  7321. var observer = observable.add(callback, mask, false, scope);
  7322. if (observer) {
  7323. result._observers.push(observer);
  7324. }
  7325. }
  7326. return result;
  7327. };
  7328. return MultiObserver;
  7329. }());
  7330. BABYLON.MultiObserver = MultiObserver;
  7331. /**
  7332. * The Observable class is a simple implementation of the Observable pattern.
  7333. * 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.
  7334. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7335. * 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).
  7336. * 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.
  7337. */
  7338. var Observable = /** @class */ (function () {
  7339. /**
  7340. * Creates a new observable
  7341. * @param onObserverAdded defines a callback to call when a new observer is added
  7342. */
  7343. function Observable(onObserverAdded) {
  7344. this._observers = new Array();
  7345. this._eventState = new EventState(0);
  7346. if (onObserverAdded) {
  7347. this._onObserverAdded = onObserverAdded;
  7348. }
  7349. }
  7350. /**
  7351. * Create a new Observer with the specified callback
  7352. * @param callback the callback that will be executed for that Observer
  7353. * @param mask the mask used to filter observers
  7354. * @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.
  7355. * @param scope optional scope for the callback to be called from
  7356. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7357. * @returns the new observer created for the callback
  7358. */
  7359. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7360. if (mask === void 0) { mask = -1; }
  7361. if (insertFirst === void 0) { insertFirst = false; }
  7362. if (scope === void 0) { scope = null; }
  7363. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7364. if (!callback) {
  7365. return null;
  7366. }
  7367. var observer = new Observer(callback, mask, scope);
  7368. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7369. if (insertFirst) {
  7370. this._observers.unshift(observer);
  7371. }
  7372. else {
  7373. this._observers.push(observer);
  7374. }
  7375. if (this._onObserverAdded) {
  7376. this._onObserverAdded(observer);
  7377. }
  7378. return observer;
  7379. };
  7380. /**
  7381. * Remove an Observer from the Observable object
  7382. * @param observer the instance of the Observer to remove
  7383. * @returns false if it doesn't belong to this Observable
  7384. */
  7385. Observable.prototype.remove = function (observer) {
  7386. if (!observer) {
  7387. return false;
  7388. }
  7389. var index = this._observers.indexOf(observer);
  7390. if (index !== -1) {
  7391. this._observers.splice(index, 1);
  7392. return true;
  7393. }
  7394. return false;
  7395. };
  7396. /**
  7397. * Remove a callback from the Observable object
  7398. * @param callback the callback to remove
  7399. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7400. * @returns false if it doesn't belong to this Observable
  7401. */
  7402. Observable.prototype.removeCallback = function (callback, scope) {
  7403. for (var index = 0; index < this._observers.length; index++) {
  7404. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7405. this._observers.splice(index, 1);
  7406. return true;
  7407. }
  7408. }
  7409. return false;
  7410. };
  7411. Observable.prototype._deferUnregister = function (observer) {
  7412. var _this = this;
  7413. observer.unregisterOnNextCall = false;
  7414. observer._willBeUnregistered = true;
  7415. BABYLON.Tools.SetImmediate(function () {
  7416. _this.remove(observer);
  7417. });
  7418. };
  7419. /**
  7420. * Notify all Observers by calling their respective callback with the given data
  7421. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7422. * @param eventData defines the data to send to all observers
  7423. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7424. * @param target defines the original target of the state
  7425. * @param currentTarget defines the current target of the state
  7426. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7427. */
  7428. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7429. if (mask === void 0) { mask = -1; }
  7430. if (!this._observers.length) {
  7431. return true;
  7432. }
  7433. var state = this._eventState;
  7434. state.mask = mask;
  7435. state.target = target;
  7436. state.currentTarget = currentTarget;
  7437. state.skipNextObservers = false;
  7438. state.lastReturnValue = eventData;
  7439. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7440. var obs = _a[_i];
  7441. if (obs._willBeUnregistered) {
  7442. continue;
  7443. }
  7444. if (obs.mask & mask) {
  7445. if (obs.scope) {
  7446. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7447. }
  7448. else {
  7449. state.lastReturnValue = obs.callback(eventData, state);
  7450. }
  7451. if (obs.unregisterOnNextCall) {
  7452. this._deferUnregister(obs);
  7453. }
  7454. }
  7455. if (state.skipNextObservers) {
  7456. return false;
  7457. }
  7458. }
  7459. return true;
  7460. };
  7461. /**
  7462. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7463. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7464. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7465. * and it is crucial that all callbacks will be executed.
  7466. * The order of the callbacks is kept, callbacks are not executed parallel.
  7467. *
  7468. * @param eventData The data to be sent to each callback
  7469. * @param mask is used to filter observers defaults to -1
  7470. * @param target defines the callback target (see EventState)
  7471. * @param currentTarget defines he current object in the bubbling phase
  7472. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7473. */
  7474. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7475. var _this = this;
  7476. if (mask === void 0) { mask = -1; }
  7477. // create an empty promise
  7478. var p = Promise.resolve(eventData);
  7479. // no observers? return this promise.
  7480. if (!this._observers.length) {
  7481. return p;
  7482. }
  7483. var state = this._eventState;
  7484. state.mask = mask;
  7485. state.target = target;
  7486. state.currentTarget = currentTarget;
  7487. state.skipNextObservers = false;
  7488. // execute one callback after another (not using Promise.all, the order is important)
  7489. this._observers.forEach(function (obs) {
  7490. if (state.skipNextObservers) {
  7491. return;
  7492. }
  7493. if (obs._willBeUnregistered) {
  7494. return;
  7495. }
  7496. if (obs.mask & mask) {
  7497. if (obs.scope) {
  7498. p = p.then(function (lastReturnedValue) {
  7499. state.lastReturnValue = lastReturnedValue;
  7500. return obs.callback.apply(obs.scope, [eventData, state]);
  7501. });
  7502. }
  7503. else {
  7504. p = p.then(function (lastReturnedValue) {
  7505. state.lastReturnValue = lastReturnedValue;
  7506. return obs.callback(eventData, state);
  7507. });
  7508. }
  7509. if (obs.unregisterOnNextCall) {
  7510. _this._deferUnregister(obs);
  7511. }
  7512. }
  7513. });
  7514. // return the eventData
  7515. return p.then(function () { return eventData; });
  7516. };
  7517. /**
  7518. * Notify a specific observer
  7519. * @param observer defines the observer to notify
  7520. * @param eventData defines the data to be sent to each callback
  7521. * @param mask is used to filter observers defaults to -1
  7522. */
  7523. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7524. if (mask === void 0) { mask = -1; }
  7525. var state = this._eventState;
  7526. state.mask = mask;
  7527. state.skipNextObservers = false;
  7528. observer.callback(eventData, state);
  7529. };
  7530. /**
  7531. * Gets a boolean indicating if the observable has at least one observer
  7532. * @returns true is the Observable has at least one Observer registered
  7533. */
  7534. Observable.prototype.hasObservers = function () {
  7535. return this._observers.length > 0;
  7536. };
  7537. /**
  7538. * Clear the list of observers
  7539. */
  7540. Observable.prototype.clear = function () {
  7541. this._observers = new Array();
  7542. this._onObserverAdded = null;
  7543. };
  7544. /**
  7545. * Clone the current observable
  7546. * @returns a new observable
  7547. */
  7548. Observable.prototype.clone = function () {
  7549. var result = new Observable();
  7550. result._observers = this._observers.slice(0);
  7551. return result;
  7552. };
  7553. /**
  7554. * Does this observable handles observer registered with a given mask
  7555. * @param mask defines the mask to be tested
  7556. * @return whether or not one observer registered with the given mask is handeled
  7557. **/
  7558. Observable.prototype.hasSpecificMask = function (mask) {
  7559. if (mask === void 0) { mask = -1; }
  7560. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7561. var obs = _a[_i];
  7562. if (obs.mask & mask || obs.mask === mask) {
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. return Observable;
  7569. }());
  7570. BABYLON.Observable = Observable;
  7571. })(BABYLON || (BABYLON = {}));
  7572. //# sourceMappingURL=babylon.observable.js.map
  7573. var BABYLON;
  7574. (function (BABYLON) {
  7575. var SmartArray = /** @class */ (function () {
  7576. function SmartArray(capacity) {
  7577. this.length = 0;
  7578. this.data = new Array(capacity);
  7579. this._id = SmartArray._GlobalId++;
  7580. }
  7581. SmartArray.prototype.push = function (value) {
  7582. this.data[this.length++] = value;
  7583. if (this.length > this.data.length) {
  7584. this.data.length *= 2;
  7585. }
  7586. };
  7587. SmartArray.prototype.forEach = function (func) {
  7588. for (var index = 0; index < this.length; index++) {
  7589. func(this.data[index]);
  7590. }
  7591. };
  7592. SmartArray.prototype.sort = function (compareFn) {
  7593. this.data.sort(compareFn);
  7594. };
  7595. SmartArray.prototype.reset = function () {
  7596. this.length = 0;
  7597. };
  7598. SmartArray.prototype.dispose = function () {
  7599. this.reset();
  7600. if (this.data) {
  7601. this.data.length = 0;
  7602. this.data = [];
  7603. }
  7604. };
  7605. SmartArray.prototype.concat = function (array) {
  7606. if (array.length === 0) {
  7607. return;
  7608. }
  7609. if (this.length + array.length > this.data.length) {
  7610. this.data.length = (this.length + array.length) * 2;
  7611. }
  7612. for (var index = 0; index < array.length; index++) {
  7613. this.data[this.length++] = (array.data || array)[index];
  7614. }
  7615. };
  7616. SmartArray.prototype.indexOf = function (value) {
  7617. var position = this.data.indexOf(value);
  7618. if (position >= this.length) {
  7619. return -1;
  7620. }
  7621. return position;
  7622. };
  7623. SmartArray.prototype.contains = function (value) {
  7624. return this.data.indexOf(value) !== -1;
  7625. };
  7626. // Statics
  7627. SmartArray._GlobalId = 0;
  7628. return SmartArray;
  7629. }());
  7630. BABYLON.SmartArray = SmartArray;
  7631. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7632. __extends(SmartArrayNoDuplicate, _super);
  7633. function SmartArrayNoDuplicate() {
  7634. var _this = _super !== null && _super.apply(this, arguments) || this;
  7635. _this._duplicateId = 0;
  7636. return _this;
  7637. }
  7638. SmartArrayNoDuplicate.prototype.push = function (value) {
  7639. _super.prototype.push.call(this, value);
  7640. if (!value.__smartArrayFlags) {
  7641. value.__smartArrayFlags = {};
  7642. }
  7643. value.__smartArrayFlags[this._id] = this._duplicateId;
  7644. };
  7645. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7646. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7647. return false;
  7648. }
  7649. this.push(value);
  7650. return true;
  7651. };
  7652. SmartArrayNoDuplicate.prototype.reset = function () {
  7653. _super.prototype.reset.call(this);
  7654. this._duplicateId++;
  7655. };
  7656. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7657. if (array.length === 0) {
  7658. return;
  7659. }
  7660. if (this.length + array.length > this.data.length) {
  7661. this.data.length = (this.length + array.length) * 2;
  7662. }
  7663. for (var index = 0; index < array.length; index++) {
  7664. var item = (array.data || array)[index];
  7665. this.pushNoDuplicate(item);
  7666. }
  7667. };
  7668. return SmartArrayNoDuplicate;
  7669. }(SmartArray));
  7670. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7671. })(BABYLON || (BABYLON = {}));
  7672. //# sourceMappingURL=babylon.smartArray.js.map
  7673. var BABYLON;
  7674. (function (BABYLON) {
  7675. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7676. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7677. var LoadFileError = /** @class */ (function (_super) {
  7678. __extends(LoadFileError, _super);
  7679. function LoadFileError(message, request) {
  7680. var _this = _super.call(this, message) || this;
  7681. _this.request = request;
  7682. _this.name = "LoadFileError";
  7683. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7684. return _this;
  7685. }
  7686. // Polyfill for Object.setPrototypeOf if necessary.
  7687. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7688. return LoadFileError;
  7689. }(Error));
  7690. BABYLON.LoadFileError = LoadFileError;
  7691. var RetryStrategy = /** @class */ (function () {
  7692. function RetryStrategy() {
  7693. }
  7694. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7695. if (maxRetries === void 0) { maxRetries = 3; }
  7696. if (baseInterval === void 0) { baseInterval = 500; }
  7697. return function (url, request, retryIndex) {
  7698. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7699. return -1;
  7700. }
  7701. return Math.pow(2, retryIndex) * baseInterval;
  7702. };
  7703. };
  7704. return RetryStrategy;
  7705. }());
  7706. BABYLON.RetryStrategy = RetryStrategy;
  7707. // Screenshots
  7708. var screenshotCanvas;
  7709. var cloneValue = function (source, destinationObject) {
  7710. if (!source)
  7711. return null;
  7712. if (source instanceof BABYLON.Mesh) {
  7713. return null;
  7714. }
  7715. if (source instanceof BABYLON.SubMesh) {
  7716. return source.clone(destinationObject);
  7717. }
  7718. else if (source.clone) {
  7719. return source.clone();
  7720. }
  7721. return null;
  7722. };
  7723. var Tools = /** @class */ (function () {
  7724. function Tools() {
  7725. }
  7726. /**
  7727. * Interpolates between a and b via alpha
  7728. * @param a The lower value (returned when alpha = 0)
  7729. * @param b The upper value (returned when alpha = 1)
  7730. * @param alpha The interpolation-factor
  7731. * @return The mixed value
  7732. */
  7733. Tools.Mix = function (a, b, alpha) {
  7734. return a * (1 - alpha) + b * alpha;
  7735. };
  7736. Tools.Instantiate = function (className) {
  7737. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7738. return Tools.RegisteredExternalClasses[className];
  7739. }
  7740. var arr = className.split(".");
  7741. var fn = (window || this);
  7742. for (var i = 0, len = arr.length; i < len; i++) {
  7743. fn = fn[arr[i]];
  7744. }
  7745. if (typeof fn !== "function") {
  7746. return null;
  7747. }
  7748. return fn;
  7749. };
  7750. /**
  7751. * Provides a slice function that will work even on IE
  7752. * @param data defines the array to slice
  7753. * @returns the new sliced array
  7754. */
  7755. Tools.Slice = function (data) {
  7756. if (data.slice) {
  7757. return data.slice();
  7758. }
  7759. return Array.prototype.slice.call(data);
  7760. };
  7761. Tools.SetImmediate = function (action) {
  7762. if (window.setImmediate) {
  7763. window.setImmediate(action);
  7764. }
  7765. else {
  7766. setTimeout(action, 1);
  7767. }
  7768. };
  7769. Tools.IsExponentOfTwo = function (value) {
  7770. var count = 1;
  7771. do {
  7772. count *= 2;
  7773. } while (count < value);
  7774. return count === value;
  7775. };
  7776. /**
  7777. * Find the next highest power of two.
  7778. * @param x Number to start search from.
  7779. * @return Next highest power of two.
  7780. */
  7781. Tools.CeilingPOT = function (x) {
  7782. x--;
  7783. x |= x >> 1;
  7784. x |= x >> 2;
  7785. x |= x >> 4;
  7786. x |= x >> 8;
  7787. x |= x >> 16;
  7788. x++;
  7789. return x;
  7790. };
  7791. /**
  7792. * Find the next lowest power of two.
  7793. * @param x Number to start search from.
  7794. * @return Next lowest power of two.
  7795. */
  7796. Tools.FloorPOT = function (x) {
  7797. x = x | (x >> 1);
  7798. x = x | (x >> 2);
  7799. x = x | (x >> 4);
  7800. x = x | (x >> 8);
  7801. x = x | (x >> 16);
  7802. return x - (x >> 1);
  7803. };
  7804. /**
  7805. * Find the nearest power of two.
  7806. * @param x Number to start search from.
  7807. * @return Next nearest power of two.
  7808. */
  7809. Tools.NearestPOT = function (x) {
  7810. var c = Tools.CeilingPOT(x);
  7811. var f = Tools.FloorPOT(x);
  7812. return (c - x) > (x - f) ? f : c;
  7813. };
  7814. Tools.GetExponentOfTwo = function (value, max, mode) {
  7815. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7816. var pot;
  7817. switch (mode) {
  7818. case BABYLON.Engine.SCALEMODE_FLOOR:
  7819. pot = Tools.FloorPOT(value);
  7820. break;
  7821. case BABYLON.Engine.SCALEMODE_NEAREST:
  7822. pot = Tools.NearestPOT(value);
  7823. break;
  7824. case BABYLON.Engine.SCALEMODE_CEILING:
  7825. default:
  7826. pot = Tools.CeilingPOT(value);
  7827. break;
  7828. }
  7829. return Math.min(pot, max);
  7830. };
  7831. Tools.GetFilename = function (path) {
  7832. var index = path.lastIndexOf("/");
  7833. if (index < 0)
  7834. return path;
  7835. return path.substring(index + 1);
  7836. };
  7837. /**
  7838. * Extracts the "folder" part of a path (everything before the filename).
  7839. * @param uri The URI to extract the info from
  7840. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7841. * @returns The "folder" part of the path
  7842. */
  7843. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7844. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7845. var index = uri.lastIndexOf("/");
  7846. if (index < 0) {
  7847. if (returnUnchangedIfNoSlash) {
  7848. return uri;
  7849. }
  7850. return "";
  7851. }
  7852. return uri.substring(0, index + 1);
  7853. };
  7854. Tools.GetDOMTextContent = function (element) {
  7855. var result = "";
  7856. var child = element.firstChild;
  7857. while (child) {
  7858. if (child.nodeType === 3) {
  7859. result += child.textContent;
  7860. }
  7861. child = child.nextSibling;
  7862. }
  7863. return result;
  7864. };
  7865. Tools.ToDegrees = function (angle) {
  7866. return angle * 180 / Math.PI;
  7867. };
  7868. Tools.ToRadians = function (angle) {
  7869. return angle * Math.PI / 180;
  7870. };
  7871. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7872. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7873. var output = "";
  7874. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7875. var i = 0;
  7876. var bytes = new Uint8Array(buffer);
  7877. while (i < bytes.length) {
  7878. chr1 = bytes[i++];
  7879. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7880. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7881. enc1 = chr1 >> 2;
  7882. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7883. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7884. enc4 = chr3 & 63;
  7885. if (isNaN(chr2)) {
  7886. enc3 = enc4 = 64;
  7887. }
  7888. else if (isNaN(chr3)) {
  7889. enc4 = 64;
  7890. }
  7891. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7892. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7893. }
  7894. return "data:image/png;base64," + output;
  7895. };
  7896. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7897. if (bias === void 0) { bias = null; }
  7898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7900. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7901. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7919. if (bias === void 0) { bias = null; }
  7920. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7921. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7922. if (!stride) {
  7923. stride = 3;
  7924. }
  7925. for (var index = start; index < start + count; index++) {
  7926. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7927. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7928. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7929. }
  7930. if (bias) {
  7931. minimum.x -= minimum.x * bias.x + bias.y;
  7932. minimum.y -= minimum.y * bias.x + bias.y;
  7933. minimum.z -= minimum.z * bias.x + bias.y;
  7934. maximum.x += maximum.x * bias.x + bias.y;
  7935. maximum.y += maximum.y * bias.x + bias.y;
  7936. maximum.z += maximum.z * bias.x + bias.y;
  7937. }
  7938. return {
  7939. minimum: minimum,
  7940. maximum: maximum
  7941. };
  7942. };
  7943. Tools.Vector2ArrayFeeder = function (array) {
  7944. return function (index) {
  7945. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7946. var length = isFloatArray ? array.length / 2 : array.length;
  7947. if (index >= length) {
  7948. return null;
  7949. }
  7950. if (isFloatArray) {
  7951. var fa = array;
  7952. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7953. }
  7954. var a = array;
  7955. return a[index];
  7956. };
  7957. };
  7958. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7959. if (bias === void 0) { bias = null; }
  7960. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7961. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7962. var i = 0;
  7963. var cur = feeder(i++);
  7964. while (cur) {
  7965. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7966. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7967. cur = feeder(i++);
  7968. }
  7969. if (bias) {
  7970. minimum.x -= minimum.x * bias.x + bias.y;
  7971. minimum.y -= minimum.y * bias.x + bias.y;
  7972. maximum.x += maximum.x * bias.x + bias.y;
  7973. maximum.y += maximum.y * bias.x + bias.y;
  7974. }
  7975. return {
  7976. minimum: minimum,
  7977. maximum: maximum
  7978. };
  7979. };
  7980. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7981. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7982. return null;
  7983. return Array.isArray(obj) ? obj : [obj];
  7984. };
  7985. // Misc.
  7986. Tools.GetPointerPrefix = function () {
  7987. var eventPrefix = "pointer";
  7988. // Check if pointer events are supported
  7989. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7990. eventPrefix = "mouse";
  7991. }
  7992. return eventPrefix;
  7993. };
  7994. /**
  7995. * @param func - the function to be called
  7996. * @param requester - the object that will request the next frame. Falls back to window.
  7997. */
  7998. Tools.QueueNewFrame = function (func, requester) {
  7999. if (!Tools.IsWindowObjectExist()) {
  8000. return setTimeout(func, 16);
  8001. }
  8002. if (!requester) {
  8003. requester = window;
  8004. }
  8005. if (requester.requestAnimationFrame) {
  8006. return requester.requestAnimationFrame(func);
  8007. }
  8008. else if (requester.msRequestAnimationFrame) {
  8009. return requester.msRequestAnimationFrame(func);
  8010. }
  8011. else if (requester.webkitRequestAnimationFrame) {
  8012. return requester.webkitRequestAnimationFrame(func);
  8013. }
  8014. else if (requester.mozRequestAnimationFrame) {
  8015. return requester.mozRequestAnimationFrame(func);
  8016. }
  8017. else if (requester.oRequestAnimationFrame) {
  8018. return requester.oRequestAnimationFrame(func);
  8019. }
  8020. else {
  8021. return window.setTimeout(func, 16);
  8022. }
  8023. };
  8024. Tools.RequestFullscreen = function (element) {
  8025. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8026. if (!requestFunction)
  8027. return;
  8028. requestFunction.call(element);
  8029. };
  8030. Tools.ExitFullscreen = function () {
  8031. if (document.exitFullscreen) {
  8032. document.exitFullscreen();
  8033. }
  8034. else if (document.mozCancelFullScreen) {
  8035. document.mozCancelFullScreen();
  8036. }
  8037. else if (document.webkitCancelFullScreen) {
  8038. document.webkitCancelFullScreen();
  8039. }
  8040. else if (document.msCancelFullScreen) {
  8041. document.msCancelFullScreen();
  8042. }
  8043. };
  8044. Tools.SetCorsBehavior = function (url, element) {
  8045. if (url && url.indexOf("data:") === 0) {
  8046. return;
  8047. }
  8048. if (Tools.CorsBehavior) {
  8049. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8050. element.crossOrigin = Tools.CorsBehavior;
  8051. }
  8052. else {
  8053. var result = Tools.CorsBehavior(url);
  8054. if (result) {
  8055. element.crossOrigin = result;
  8056. }
  8057. }
  8058. }
  8059. };
  8060. // External files
  8061. Tools.CleanUrl = function (url) {
  8062. url = url.replace(/#/mg, "%23");
  8063. return url;
  8064. };
  8065. Tools.LoadImage = function (url, onLoad, onError, database) {
  8066. if (url instanceof ArrayBuffer) {
  8067. url = Tools.EncodeArrayBufferTobase64(url);
  8068. }
  8069. url = Tools.CleanUrl(url);
  8070. url = Tools.PreprocessUrl(url);
  8071. var img = new Image();
  8072. Tools.SetCorsBehavior(url, img);
  8073. var loadHandler = function () {
  8074. img.removeEventListener("load", loadHandler);
  8075. img.removeEventListener("error", errorHandler);
  8076. onLoad(img);
  8077. };
  8078. var errorHandler = function (err) {
  8079. img.removeEventListener("load", loadHandler);
  8080. img.removeEventListener("error", errorHandler);
  8081. Tools.Error("Error while trying to load image: " + url);
  8082. if (onError) {
  8083. onError("Error while trying to load image: " + url, err);
  8084. }
  8085. };
  8086. img.addEventListener("load", loadHandler);
  8087. img.addEventListener("error", errorHandler);
  8088. var noIndexedDB = function () {
  8089. img.src = url;
  8090. };
  8091. var loadFromIndexedDB = function () {
  8092. if (database) {
  8093. database.loadImageFromDB(url, img);
  8094. }
  8095. };
  8096. //ANY database to do!
  8097. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8098. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8099. }
  8100. else {
  8101. if (url.indexOf("file:") !== -1) {
  8102. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8103. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8104. try {
  8105. var blobURL;
  8106. try {
  8107. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8108. }
  8109. catch (ex) {
  8110. // Chrome doesn't support oneTimeOnly parameter
  8111. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8112. }
  8113. img.src = blobURL;
  8114. }
  8115. catch (e) {
  8116. img.src = "";
  8117. }
  8118. return img;
  8119. }
  8120. }
  8121. noIndexedDB();
  8122. }
  8123. return img;
  8124. };
  8125. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. // If file and file input are set
  8129. if (url.indexOf("file:") !== -1) {
  8130. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8131. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8132. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8133. }
  8134. }
  8135. var loadUrl = Tools.BaseUrl + url;
  8136. var aborted = false;
  8137. var fileRequest = {
  8138. onCompleteObservable: new BABYLON.Observable(),
  8139. abort: function () { return aborted = true; },
  8140. };
  8141. var requestFile = function () {
  8142. var request = new XMLHttpRequest();
  8143. var retryHandle = null;
  8144. fileRequest.abort = function () {
  8145. aborted = true;
  8146. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8147. request.abort();
  8148. }
  8149. if (retryHandle !== null) {
  8150. clearTimeout(retryHandle);
  8151. retryHandle = null;
  8152. }
  8153. };
  8154. var retryLoop = function (retryIndex) {
  8155. request.open('GET', loadUrl, true);
  8156. if (useArrayBuffer) {
  8157. request.responseType = "arraybuffer";
  8158. }
  8159. if (onProgress) {
  8160. request.addEventListener("progress", onProgress);
  8161. }
  8162. var onLoadEnd = function () {
  8163. request.removeEventListener("loadend", onLoadEnd);
  8164. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8165. fileRequest.onCompleteObservable.clear();
  8166. };
  8167. request.addEventListener("loadend", onLoadEnd);
  8168. var onReadyStateChange = function () {
  8169. if (aborted) {
  8170. return;
  8171. }
  8172. // In case of undefined state in some browsers.
  8173. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8174. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8175. request.removeEventListener("readystatechange", onReadyStateChange);
  8176. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8177. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8178. return;
  8179. }
  8180. var retryStrategy = Tools.DefaultRetryStrategy;
  8181. if (retryStrategy) {
  8182. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8183. if (waitTime !== -1) {
  8184. // Prevent the request from completing for retry.
  8185. request.removeEventListener("loadend", onLoadEnd);
  8186. request = new XMLHttpRequest();
  8187. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8188. return;
  8189. }
  8190. }
  8191. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8192. if (onError) {
  8193. onError(request, e);
  8194. }
  8195. else {
  8196. throw e;
  8197. }
  8198. }
  8199. };
  8200. request.addEventListener("readystatechange", onReadyStateChange);
  8201. request.send();
  8202. };
  8203. retryLoop(0);
  8204. };
  8205. // Caching all files
  8206. if (database && database.enableSceneOffline) {
  8207. var noIndexedDB_1 = function () {
  8208. if (!aborted) {
  8209. requestFile();
  8210. }
  8211. };
  8212. var loadFromIndexedDB = function () {
  8213. // TODO: database needs to support aborting and should return a IFileRequest
  8214. if (aborted) {
  8215. return;
  8216. }
  8217. if (database) {
  8218. database.loadFileFromDB(url, function (data) {
  8219. if (!aborted) {
  8220. onSuccess(data);
  8221. }
  8222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8223. }, onProgress ? function (event) {
  8224. if (!aborted) {
  8225. onProgress(event);
  8226. }
  8227. } : undefined, noIndexedDB_1, useArrayBuffer);
  8228. }
  8229. };
  8230. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8231. }
  8232. else {
  8233. requestFile();
  8234. }
  8235. return fileRequest;
  8236. };
  8237. /**
  8238. * Load a script (identified by an url). When the url returns, the
  8239. * content of this file is added into a new script element, attached to the DOM (body element)
  8240. */
  8241. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8242. var head = document.getElementsByTagName('head')[0];
  8243. var script = document.createElement('script');
  8244. script.type = 'text/javascript';
  8245. script.src = scriptUrl;
  8246. script.onload = function () {
  8247. if (onSuccess) {
  8248. onSuccess();
  8249. }
  8250. };
  8251. script.onerror = function (e) {
  8252. if (onError) {
  8253. onError("Unable to load script", e);
  8254. }
  8255. };
  8256. head.appendChild(script);
  8257. };
  8258. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8259. var reader = new FileReader();
  8260. var request = {
  8261. onCompleteObservable: new BABYLON.Observable(),
  8262. abort: function () { return reader.abort(); },
  8263. };
  8264. reader.onloadend = function (e) {
  8265. request.onCompleteObservable.notifyObservers(request);
  8266. };
  8267. reader.onload = function (e) {
  8268. //target doesn't have result from ts 1.3
  8269. callback(e.target['result']);
  8270. };
  8271. reader.onprogress = progressCallback;
  8272. reader.readAsDataURL(fileToLoad);
  8273. return request;
  8274. };
  8275. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8276. var reader = new FileReader();
  8277. var request = {
  8278. onCompleteObservable: new BABYLON.Observable(),
  8279. abort: function () { return reader.abort(); },
  8280. };
  8281. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8282. reader.onerror = function (e) {
  8283. Tools.Log("Error while reading file: " + fileToLoad.name);
  8284. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8285. };
  8286. reader.onload = function (e) {
  8287. //target doesn't have result from ts 1.3
  8288. callback(e.target['result']);
  8289. };
  8290. if (progressCallBack) {
  8291. reader.onprogress = progressCallBack;
  8292. }
  8293. if (!useArrayBuffer) {
  8294. // Asynchronous read
  8295. reader.readAsText(fileToLoad);
  8296. }
  8297. else {
  8298. reader.readAsArrayBuffer(fileToLoad);
  8299. }
  8300. return request;
  8301. };
  8302. //returns a downloadable url to a file content.
  8303. Tools.FileAsURL = function (content) {
  8304. var fileBlob = new Blob([content]);
  8305. var url = window.URL || window.webkitURL;
  8306. var link = url.createObjectURL(fileBlob);
  8307. return link;
  8308. };
  8309. // Misc.
  8310. Tools.Format = function (value, decimals) {
  8311. if (decimals === void 0) { decimals = 2; }
  8312. return value.toFixed(decimals);
  8313. };
  8314. Tools.CheckExtends = function (v, min, max) {
  8315. if (v.x < min.x)
  8316. min.x = v.x;
  8317. if (v.y < min.y)
  8318. min.y = v.y;
  8319. if (v.z < min.z)
  8320. min.z = v.z;
  8321. if (v.x > max.x)
  8322. max.x = v.x;
  8323. if (v.y > max.y)
  8324. max.y = v.y;
  8325. if (v.z > max.z)
  8326. max.z = v.z;
  8327. };
  8328. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8329. for (var prop in source) {
  8330. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8331. continue;
  8332. }
  8333. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8334. continue;
  8335. }
  8336. var sourceValue = source[prop];
  8337. var typeOfSourceValue = typeof sourceValue;
  8338. if (typeOfSourceValue === "function") {
  8339. continue;
  8340. }
  8341. if (typeOfSourceValue === "object") {
  8342. if (sourceValue instanceof Array) {
  8343. destination[prop] = [];
  8344. if (sourceValue.length > 0) {
  8345. if (typeof sourceValue[0] == "object") {
  8346. for (var index = 0; index < sourceValue.length; index++) {
  8347. var clonedValue = cloneValue(sourceValue[index], destination);
  8348. if (destination[prop].indexOf(clonedValue) === -1) {
  8349. destination[prop].push(clonedValue);
  8350. }
  8351. }
  8352. }
  8353. else {
  8354. destination[prop] = sourceValue.slice(0);
  8355. }
  8356. }
  8357. }
  8358. else {
  8359. destination[prop] = cloneValue(sourceValue, destination);
  8360. }
  8361. }
  8362. else {
  8363. destination[prop] = sourceValue;
  8364. }
  8365. }
  8366. };
  8367. Tools.IsEmpty = function (obj) {
  8368. for (var i in obj) {
  8369. if (obj.hasOwnProperty(i)) {
  8370. return false;
  8371. }
  8372. }
  8373. return true;
  8374. };
  8375. Tools.RegisterTopRootEvents = function (events) {
  8376. for (var index = 0; index < events.length; index++) {
  8377. var event = events[index];
  8378. window.addEventListener(event.name, event.handler, false);
  8379. try {
  8380. if (window.parent) {
  8381. window.parent.addEventListener(event.name, event.handler, false);
  8382. }
  8383. }
  8384. catch (e) {
  8385. // Silently fails...
  8386. }
  8387. }
  8388. };
  8389. Tools.UnregisterTopRootEvents = function (events) {
  8390. for (var index = 0; index < events.length; index++) {
  8391. var event = events[index];
  8392. window.removeEventListener(event.name, event.handler);
  8393. try {
  8394. if (window.parent) {
  8395. window.parent.removeEventListener(event.name, event.handler);
  8396. }
  8397. }
  8398. catch (e) {
  8399. // Silently fails...
  8400. }
  8401. }
  8402. };
  8403. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8404. if (mimeType === void 0) { mimeType = "image/png"; }
  8405. // Read the contents of the framebuffer
  8406. var numberOfChannelsByLine = width * 4;
  8407. var halfHeight = height / 2;
  8408. //Reading datas from WebGL
  8409. var data = engine.readPixels(0, 0, width, height);
  8410. //To flip image on Y axis.
  8411. for (var i = 0; i < halfHeight; i++) {
  8412. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8413. var currentCell = j + i * numberOfChannelsByLine;
  8414. var targetLine = height - i - 1;
  8415. var targetCell = j + targetLine * numberOfChannelsByLine;
  8416. var temp = data[currentCell];
  8417. data[currentCell] = data[targetCell];
  8418. data[targetCell] = temp;
  8419. }
  8420. }
  8421. // Create a 2D canvas to store the result
  8422. if (!screenshotCanvas) {
  8423. screenshotCanvas = document.createElement('canvas');
  8424. }
  8425. screenshotCanvas.width = width;
  8426. screenshotCanvas.height = height;
  8427. var context = screenshotCanvas.getContext('2d');
  8428. if (context) {
  8429. // Copy the pixels to a 2D canvas
  8430. var imageData = context.createImageData(width, height);
  8431. var castData = (imageData.data);
  8432. castData.set(data);
  8433. context.putImageData(imageData, 0, 0);
  8434. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8435. }
  8436. };
  8437. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8438. if (mimeType === void 0) { mimeType = "image/png"; }
  8439. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8440. if (successCallback) {
  8441. successCallback(base64Image);
  8442. }
  8443. else {
  8444. // We need HTMLCanvasElement.toBlob for HD screenshots
  8445. if (!screenshotCanvas.toBlob) {
  8446. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8447. screenshotCanvas.toBlob = function (callback, type, quality) {
  8448. var _this = this;
  8449. setTimeout(function () {
  8450. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8451. for (var i = 0; i < len; i++) {
  8452. arr[i] = binStr.charCodeAt(i);
  8453. }
  8454. callback(new Blob([arr], { type: type || 'image/png' }));
  8455. });
  8456. };
  8457. }
  8458. screenshotCanvas.toBlob(function (blob) {
  8459. var url = URL.createObjectURL(blob);
  8460. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8461. if (("download" in document.createElement("a"))) {
  8462. var a = window.document.createElement("a");
  8463. a.href = url;
  8464. if (fileName) {
  8465. a.setAttribute("download", fileName);
  8466. }
  8467. else {
  8468. var date = new Date();
  8469. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8470. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8471. }
  8472. window.document.body.appendChild(a);
  8473. a.addEventListener("click", function () {
  8474. if (a.parentElement) {
  8475. a.parentElement.removeChild(a);
  8476. }
  8477. });
  8478. a.click();
  8479. }
  8480. else {
  8481. var newWindow = window.open("");
  8482. if (!newWindow)
  8483. return;
  8484. var img = newWindow.document.createElement("img");
  8485. img.onload = function () {
  8486. // no longer need to read the blob so it's revoked
  8487. URL.revokeObjectURL(url);
  8488. };
  8489. img.src = url;
  8490. newWindow.document.body.appendChild(img);
  8491. }
  8492. });
  8493. }
  8494. };
  8495. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8496. if (mimeType === void 0) { mimeType = "image/png"; }
  8497. var width;
  8498. var height;
  8499. // If a precision value is specified
  8500. if (size.precision) {
  8501. width = Math.round(engine.getRenderWidth() * size.precision);
  8502. height = Math.round(width / engine.getAspectRatio(camera));
  8503. }
  8504. else if (size.width && size.height) {
  8505. width = size.width;
  8506. height = size.height;
  8507. }
  8508. else if (size.width && !size.height) {
  8509. width = size.width;
  8510. height = Math.round(width / engine.getAspectRatio(camera));
  8511. }
  8512. else if (size.height && !size.width) {
  8513. height = size.height;
  8514. width = Math.round(height * engine.getAspectRatio(camera));
  8515. }
  8516. else if (!isNaN(size)) {
  8517. height = size;
  8518. width = size;
  8519. }
  8520. else {
  8521. Tools.Error("Invalid 'size' parameter !");
  8522. return;
  8523. }
  8524. if (!screenshotCanvas) {
  8525. screenshotCanvas = document.createElement('canvas');
  8526. }
  8527. screenshotCanvas.width = width;
  8528. screenshotCanvas.height = height;
  8529. var renderContext = screenshotCanvas.getContext("2d");
  8530. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8531. var newWidth = width;
  8532. var newHeight = newWidth / ratio;
  8533. if (newHeight > height) {
  8534. newHeight = height;
  8535. newWidth = newHeight * ratio;
  8536. }
  8537. var offsetX = Math.max(0, width - newWidth) / 2;
  8538. var offsetY = Math.max(0, height - newHeight) / 2;
  8539. var renderingCanvas = engine.getRenderingCanvas();
  8540. if (renderContext && renderingCanvas) {
  8541. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8542. }
  8543. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8544. };
  8545. /**
  8546. * Generates an image screenshot from the specified camera.
  8547. *
  8548. * @param engine The engine to use for rendering
  8549. * @param camera The camera to use for rendering
  8550. * @param size This parameter can be set to a single number or to an object with the
  8551. * following (optional) properties: precision, width, height. If a single number is passed,
  8552. * it will be used for both width and height. If an object is passed, the screenshot size
  8553. * will be derived from the parameters. The precision property is a multiplier allowing
  8554. * rendering at a higher or lower resolution.
  8555. * @param successCallback The callback receives a single parameter which contains the
  8556. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8557. * src parameter of an <img> to display it.
  8558. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8559. * Check your browser for supported MIME types.
  8560. * @param samples Texture samples (default: 1)
  8561. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8562. * @param fileName A name for for the downloaded file.
  8563. * @constructor
  8564. */
  8565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8566. if (mimeType === void 0) { mimeType = "image/png"; }
  8567. if (samples === void 0) { samples = 1; }
  8568. if (antialiasing === void 0) { antialiasing = false; }
  8569. var width;
  8570. var height;
  8571. //If a precision value is specified
  8572. if (size.precision) {
  8573. width = Math.round(engine.getRenderWidth() * size.precision);
  8574. height = Math.round(width / engine.getAspectRatio(camera));
  8575. size = { width: width, height: height };
  8576. }
  8577. else if (size.width && size.height) {
  8578. width = size.width;
  8579. height = size.height;
  8580. }
  8581. else if (size.width && !size.height) {
  8582. width = size.width;
  8583. height = Math.round(width / engine.getAspectRatio(camera));
  8584. size = { width: width, height: height };
  8585. }
  8586. else if (size.height && !size.width) {
  8587. height = size.height;
  8588. width = Math.round(height * engine.getAspectRatio(camera));
  8589. size = { width: width, height: height };
  8590. }
  8591. else if (!isNaN(size)) {
  8592. height = size;
  8593. width = size;
  8594. }
  8595. else {
  8596. Tools.Error("Invalid 'size' parameter !");
  8597. return;
  8598. }
  8599. var scene = camera.getScene();
  8600. var previousCamera = null;
  8601. if (scene.activeCamera !== camera) {
  8602. previousCamera = scene.activeCamera;
  8603. scene.activeCamera = camera;
  8604. }
  8605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8607. texture.renderList = null;
  8608. texture.samples = samples;
  8609. if (antialiasing) {
  8610. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8611. }
  8612. texture.onAfterRenderObservable.add(function () {
  8613. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8614. });
  8615. scene.incrementRenderId();
  8616. scene.resetCachedMaterial();
  8617. texture.render(true);
  8618. texture.dispose();
  8619. if (previousCamera) {
  8620. scene.activeCamera = previousCamera;
  8621. }
  8622. camera.getProjectionMatrix(true); // Force cache refresh;
  8623. };
  8624. // XHR response validator for local file scenario
  8625. Tools.ValidateXHRData = function (xhr, dataType) {
  8626. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8627. if (dataType === void 0) { dataType = 7; }
  8628. try {
  8629. if (dataType & 1) {
  8630. if (xhr.responseText && xhr.responseText.length > 0) {
  8631. return true;
  8632. }
  8633. else if (dataType === 1) {
  8634. return false;
  8635. }
  8636. }
  8637. if (dataType & 2) {
  8638. // Check header width and height since there is no "TGA" magic number
  8639. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8640. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8641. return true;
  8642. }
  8643. else if (dataType === 2) {
  8644. return false;
  8645. }
  8646. }
  8647. if (dataType & 4) {
  8648. // Check for the "DDS" magic number
  8649. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8650. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8651. return true;
  8652. }
  8653. else {
  8654. return false;
  8655. }
  8656. }
  8657. }
  8658. catch (e) {
  8659. // Global protection
  8660. }
  8661. return false;
  8662. };
  8663. /**
  8664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8665. * Be aware Math.random() could cause collisions, but:
  8666. * "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"
  8667. */
  8668. Tools.RandomId = function () {
  8669. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8670. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8671. return v.toString(16);
  8672. });
  8673. };
  8674. /**
  8675. * Test if the given uri is a base64 string.
  8676. * @param uri The uri to test
  8677. * @return True if the uri is a base64 string or false otherwise.
  8678. */
  8679. Tools.IsBase64 = function (uri) {
  8680. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8681. };
  8682. /**
  8683. * Decode the given base64 uri.
  8684. * @param uri The uri to decode
  8685. * @return The decoded base64 data.
  8686. */
  8687. Tools.DecodeBase64 = function (uri) {
  8688. var decodedString = atob(uri.split(",")[1]);
  8689. var bufferLength = decodedString.length;
  8690. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8691. for (var i = 0; i < bufferLength; i++) {
  8692. bufferView[i] = decodedString.charCodeAt(i);
  8693. }
  8694. return bufferView.buffer;
  8695. };
  8696. Object.defineProperty(Tools, "NoneLogLevel", {
  8697. get: function () {
  8698. return Tools._NoneLogLevel;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(Tools, "MessageLogLevel", {
  8704. get: function () {
  8705. return Tools._MessageLogLevel;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Tools, "WarningLogLevel", {
  8711. get: function () {
  8712. return Tools._WarningLogLevel;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Object.defineProperty(Tools, "ErrorLogLevel", {
  8718. get: function () {
  8719. return Tools._ErrorLogLevel;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(Tools, "AllLogLevel", {
  8725. get: function () {
  8726. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Tools._AddLogEntry = function (entry) {
  8732. Tools._LogCache = entry + Tools._LogCache;
  8733. if (Tools.OnNewCacheEntry) {
  8734. Tools.OnNewCacheEntry(entry);
  8735. }
  8736. };
  8737. Tools._FormatMessage = function (message) {
  8738. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8739. var date = new Date();
  8740. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8741. };
  8742. Tools._LogDisabled = function (message) {
  8743. // nothing to do
  8744. };
  8745. Tools._LogEnabled = function (message) {
  8746. var formattedMessage = Tools._FormatMessage(message);
  8747. console.log("BJS - " + formattedMessage);
  8748. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8749. Tools._AddLogEntry(entry);
  8750. };
  8751. Tools._WarnDisabled = function (message) {
  8752. // nothing to do
  8753. };
  8754. Tools._WarnEnabled = function (message) {
  8755. var formattedMessage = Tools._FormatMessage(message);
  8756. console.warn("BJS - " + formattedMessage);
  8757. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8758. Tools._AddLogEntry(entry);
  8759. };
  8760. Tools._ErrorDisabled = function (message) {
  8761. // nothing to do
  8762. };
  8763. Tools._ErrorEnabled = function (message) {
  8764. Tools.errorsCount++;
  8765. var formattedMessage = Tools._FormatMessage(message);
  8766. console.error("BJS - " + formattedMessage);
  8767. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8768. Tools._AddLogEntry(entry);
  8769. };
  8770. Object.defineProperty(Tools, "LogCache", {
  8771. get: function () {
  8772. return Tools._LogCache;
  8773. },
  8774. enumerable: true,
  8775. configurable: true
  8776. });
  8777. Tools.ClearLogCache = function () {
  8778. Tools._LogCache = "";
  8779. Tools.errorsCount = 0;
  8780. };
  8781. Object.defineProperty(Tools, "LogLevels", {
  8782. set: function (level) {
  8783. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8784. Tools.Log = Tools._LogEnabled;
  8785. }
  8786. else {
  8787. Tools.Log = Tools._LogDisabled;
  8788. }
  8789. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8790. Tools.Warn = Tools._WarnEnabled;
  8791. }
  8792. else {
  8793. Tools.Warn = Tools._WarnDisabled;
  8794. }
  8795. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8796. Tools.Error = Tools._ErrorEnabled;
  8797. }
  8798. else {
  8799. Tools.Error = Tools._ErrorDisabled;
  8800. }
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Tools.IsWindowObjectExist = function () {
  8806. return (typeof window) !== "undefined";
  8807. };
  8808. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8809. get: function () {
  8810. return Tools._PerformanceNoneLogLevel;
  8811. },
  8812. enumerable: true,
  8813. configurable: true
  8814. });
  8815. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8816. get: function () {
  8817. return Tools._PerformanceUserMarkLogLevel;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8823. get: function () {
  8824. return Tools._PerformanceConsoleLogLevel;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8830. set: function (level) {
  8831. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8832. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8833. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8834. return;
  8835. }
  8836. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8837. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8838. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8839. return;
  8840. }
  8841. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8842. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8848. };
  8849. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8850. };
  8851. Tools._StartUserMark = function (counterName, condition) {
  8852. if (condition === void 0) { condition = true; }
  8853. if (!Tools._performance) {
  8854. if (!Tools.IsWindowObjectExist()) {
  8855. return;
  8856. }
  8857. Tools._performance = window.performance;
  8858. }
  8859. if (!condition || !Tools._performance.mark) {
  8860. return;
  8861. }
  8862. Tools._performance.mark(counterName + "-Begin");
  8863. };
  8864. Tools._EndUserMark = function (counterName, condition) {
  8865. if (condition === void 0) { condition = true; }
  8866. if (!condition || !Tools._performance.mark) {
  8867. return;
  8868. }
  8869. Tools._performance.mark(counterName + "-End");
  8870. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8871. };
  8872. Tools._StartPerformanceConsole = function (counterName, condition) {
  8873. if (condition === void 0) { condition = true; }
  8874. if (!condition) {
  8875. return;
  8876. }
  8877. Tools._StartUserMark(counterName, condition);
  8878. if (console.time) {
  8879. console.time(counterName);
  8880. }
  8881. };
  8882. Tools._EndPerformanceConsole = function (counterName, condition) {
  8883. if (condition === void 0) { condition = true; }
  8884. if (!condition) {
  8885. return;
  8886. }
  8887. Tools._EndUserMark(counterName, condition);
  8888. if (console.time) {
  8889. console.timeEnd(counterName);
  8890. }
  8891. };
  8892. Object.defineProperty(Tools, "Now", {
  8893. get: function () {
  8894. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8895. return window.performance.now();
  8896. }
  8897. return new Date().getTime();
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. /**
  8903. * This method will return the name of the class used to create the instance of the given object.
  8904. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8905. * @param object the object to get the class name from
  8906. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8907. */
  8908. Tools.GetClassName = function (object, isType) {
  8909. if (isType === void 0) { isType = false; }
  8910. var name = null;
  8911. if (!isType && object.getClassName) {
  8912. name = object.getClassName();
  8913. }
  8914. else {
  8915. if (object instanceof Object) {
  8916. var classObj = isType ? object : Object.getPrototypeOf(object);
  8917. name = classObj.constructor["__bjsclassName__"];
  8918. }
  8919. if (!name) {
  8920. name = typeof object;
  8921. }
  8922. }
  8923. return name;
  8924. };
  8925. Tools.First = function (array, predicate) {
  8926. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8927. var el = array_1[_i];
  8928. if (predicate(el)) {
  8929. return el;
  8930. }
  8931. }
  8932. return null;
  8933. };
  8934. /**
  8935. * This method will return the name of the full name of the class, including its owning module (if any).
  8936. * 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).
  8937. * @param object the object to get the class name from
  8938. * @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.
  8939. */
  8940. Tools.getFullClassName = function (object, isType) {
  8941. if (isType === void 0) { isType = false; }
  8942. var className = null;
  8943. var moduleName = null;
  8944. if (!isType && object.getClassName) {
  8945. className = object.getClassName();
  8946. }
  8947. else {
  8948. if (object instanceof Object) {
  8949. var classObj = isType ? object : Object.getPrototypeOf(object);
  8950. className = classObj.constructor["__bjsclassName__"];
  8951. moduleName = classObj.constructor["__bjsmoduleName__"];
  8952. }
  8953. if (!className) {
  8954. className = typeof object;
  8955. }
  8956. }
  8957. if (!className) {
  8958. return null;
  8959. }
  8960. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8961. };
  8962. /**
  8963. * 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.
  8964. * @param array
  8965. */
  8966. Tools.arrayOrStringFeeder = function (array) {
  8967. return function (index) {
  8968. if (index >= array.length) {
  8969. return null;
  8970. }
  8971. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8972. if (val && val.getHashCode) {
  8973. val = val.getHashCode();
  8974. }
  8975. if (typeof val === "string") {
  8976. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8977. }
  8978. return val;
  8979. };
  8980. };
  8981. /**
  8982. * Compute the hashCode of a stream of number
  8983. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8984. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8985. * @return the hash code computed
  8986. */
  8987. Tools.hashCodeFromStream = function (feeder) {
  8988. // Based from here: http://stackoverflow.com/a/7616484/802124
  8989. var hash = 0;
  8990. var index = 0;
  8991. var chr = feeder(index++);
  8992. while (chr != null) {
  8993. hash = ((hash << 5) - hash) + chr;
  8994. hash |= 0; // Convert to 32bit integer
  8995. chr = feeder(index++);
  8996. }
  8997. return hash;
  8998. };
  8999. /**
  9000. * Returns a promise that resolves after the given amount of time.
  9001. * @param delay Number of milliseconds to delay
  9002. * @returns Promise that resolves after the given amount of time
  9003. */
  9004. Tools.DelayAsync = function (delay) {
  9005. return new Promise(function (resolve) {
  9006. setTimeout(function () {
  9007. resolve();
  9008. }, delay);
  9009. });
  9010. };
  9011. Tools.BaseUrl = "";
  9012. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9013. /**
  9014. * Default behaviour for cors in the application.
  9015. * It can be a string if the expected behavior is identical in the entire app.
  9016. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9017. */
  9018. Tools.CorsBehavior = "anonymous";
  9019. Tools.UseFallbackTexture = true;
  9020. /**
  9021. * Use this object to register external classes like custom textures or material
  9022. * to allow the laoders to instantiate them
  9023. */
  9024. Tools.RegisteredExternalClasses = {};
  9025. // Used in case of a texture loading problem
  9026. 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";
  9027. Tools.PreprocessUrl = function (url) {
  9028. return url;
  9029. };
  9030. // Logs
  9031. Tools._NoneLogLevel = 0;
  9032. Tools._MessageLogLevel = 1;
  9033. Tools._WarningLogLevel = 2;
  9034. Tools._ErrorLogLevel = 4;
  9035. Tools._LogCache = "";
  9036. Tools.errorsCount = 0;
  9037. Tools.Log = Tools._LogEnabled;
  9038. Tools.Warn = Tools._WarnEnabled;
  9039. Tools.Error = Tools._ErrorEnabled;
  9040. // Performances
  9041. Tools._PerformanceNoneLogLevel = 0;
  9042. Tools._PerformanceUserMarkLogLevel = 1;
  9043. Tools._PerformanceConsoleLogLevel = 2;
  9044. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9045. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9046. return Tools;
  9047. }());
  9048. BABYLON.Tools = Tools;
  9049. /**
  9050. * This class is used to track a performance counter which is number based.
  9051. * The user has access to many properties which give statistics of different nature
  9052. *
  9053. * The implementer can track two kinds of Performance Counter: time and count
  9054. * 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.
  9055. * 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.
  9056. */
  9057. var PerfCounter = /** @class */ (function () {
  9058. function PerfCounter() {
  9059. this._startMonitoringTime = 0;
  9060. this._min = 0;
  9061. this._max = 0;
  9062. this._average = 0;
  9063. this._lastSecAverage = 0;
  9064. this._current = 0;
  9065. this._totalValueCount = 0;
  9066. this._totalAccumulated = 0;
  9067. this._lastSecAccumulated = 0;
  9068. this._lastSecTime = 0;
  9069. this._lastSecValueCount = 0;
  9070. }
  9071. Object.defineProperty(PerfCounter.prototype, "min", {
  9072. /**
  9073. * Returns the smallest value ever
  9074. */
  9075. get: function () {
  9076. return this._min;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(PerfCounter.prototype, "max", {
  9082. /**
  9083. * Returns the biggest value ever
  9084. */
  9085. get: function () {
  9086. return this._max;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(PerfCounter.prototype, "average", {
  9092. /**
  9093. * Returns the average value since the performance counter is running
  9094. */
  9095. get: function () {
  9096. return this._average;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9102. /**
  9103. * Returns the average value of the last second the counter was monitored
  9104. */
  9105. get: function () {
  9106. return this._lastSecAverage;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(PerfCounter.prototype, "current", {
  9112. /**
  9113. * Returns the current value
  9114. */
  9115. get: function () {
  9116. return this._current;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(PerfCounter.prototype, "total", {
  9122. get: function () {
  9123. return this._totalAccumulated;
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. Object.defineProperty(PerfCounter.prototype, "count", {
  9129. get: function () {
  9130. return this._totalValueCount;
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. /**
  9136. * Call this method to start monitoring a new frame.
  9137. * 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.
  9138. */
  9139. PerfCounter.prototype.fetchNewFrame = function () {
  9140. this._totalValueCount++;
  9141. this._current = 0;
  9142. this._lastSecValueCount++;
  9143. };
  9144. /**
  9145. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9146. * @param newCount the count value to add to the monitored count
  9147. * @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.
  9148. */
  9149. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9150. if (!PerfCounter.Enabled) {
  9151. return;
  9152. }
  9153. this._current += newCount;
  9154. if (fetchResult) {
  9155. this._fetchResult();
  9156. }
  9157. };
  9158. /**
  9159. * Start monitoring this performance counter
  9160. */
  9161. PerfCounter.prototype.beginMonitoring = function () {
  9162. if (!PerfCounter.Enabled) {
  9163. return;
  9164. }
  9165. this._startMonitoringTime = Tools.Now;
  9166. };
  9167. /**
  9168. * Compute the time lapsed since the previous beginMonitoring() call.
  9169. * @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
  9170. */
  9171. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9172. if (newFrame === void 0) { newFrame = true; }
  9173. if (!PerfCounter.Enabled) {
  9174. return;
  9175. }
  9176. if (newFrame) {
  9177. this.fetchNewFrame();
  9178. }
  9179. var currentTime = Tools.Now;
  9180. this._current = currentTime - this._startMonitoringTime;
  9181. if (newFrame) {
  9182. this._fetchResult();
  9183. }
  9184. };
  9185. PerfCounter.prototype._fetchResult = function () {
  9186. this._totalAccumulated += this._current;
  9187. this._lastSecAccumulated += this._current;
  9188. // Min/Max update
  9189. this._min = Math.min(this._min, this._current);
  9190. this._max = Math.max(this._max, this._current);
  9191. this._average = this._totalAccumulated / this._totalValueCount;
  9192. // Reset last sec?
  9193. var now = Tools.Now;
  9194. if ((now - this._lastSecTime) > 1000) {
  9195. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9196. this._lastSecTime = now;
  9197. this._lastSecAccumulated = 0;
  9198. this._lastSecValueCount = 0;
  9199. }
  9200. };
  9201. PerfCounter.Enabled = true;
  9202. return PerfCounter;
  9203. }());
  9204. BABYLON.PerfCounter = PerfCounter;
  9205. /**
  9206. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9207. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9208. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9209. * @param name The name of the class, case should be preserved
  9210. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9211. */
  9212. function className(name, module) {
  9213. return function (target) {
  9214. target["__bjsclassName__"] = name;
  9215. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9216. };
  9217. }
  9218. BABYLON.className = className;
  9219. /**
  9220. * An implementation of a loop for asynchronous functions.
  9221. */
  9222. var AsyncLoop = /** @class */ (function () {
  9223. /**
  9224. * Constroctor.
  9225. * @param iterations the number of iterations.
  9226. * @param _fn the function to run each iteration
  9227. * @param _successCallback the callback that will be called upon succesful execution
  9228. * @param offset starting offset.
  9229. */
  9230. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9231. if (offset === void 0) { offset = 0; }
  9232. this.iterations = iterations;
  9233. this._fn = _fn;
  9234. this._successCallback = _successCallback;
  9235. this.index = offset - 1;
  9236. this._done = false;
  9237. }
  9238. /**
  9239. * Execute the next iteration. Must be called after the last iteration was finished.
  9240. */
  9241. AsyncLoop.prototype.executeNext = function () {
  9242. if (!this._done) {
  9243. if (this.index + 1 < this.iterations) {
  9244. ++this.index;
  9245. this._fn(this);
  9246. }
  9247. else {
  9248. this.breakLoop();
  9249. }
  9250. }
  9251. };
  9252. /**
  9253. * Break the loop and run the success callback.
  9254. */
  9255. AsyncLoop.prototype.breakLoop = function () {
  9256. this._done = true;
  9257. this._successCallback();
  9258. };
  9259. /**
  9260. * Helper function
  9261. */
  9262. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9263. if (offset === void 0) { offset = 0; }
  9264. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9265. loop.executeNext();
  9266. return loop;
  9267. };
  9268. /**
  9269. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9270. * @param iterations total number of iterations
  9271. * @param syncedIterations number of synchronous iterations in each async iteration.
  9272. * @param fn the function to call each iteration.
  9273. * @param callback a success call back that will be called when iterating stops.
  9274. * @param breakFunction a break condition (optional)
  9275. * @param timeout timeout settings for the setTimeout function. default - 0.
  9276. * @constructor
  9277. */
  9278. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9279. if (timeout === void 0) { timeout = 0; }
  9280. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9281. if (breakFunction && breakFunction())
  9282. loop.breakLoop();
  9283. else {
  9284. setTimeout(function () {
  9285. for (var i = 0; i < syncedIterations; ++i) {
  9286. var iteration = (loop.index * syncedIterations) + i;
  9287. if (iteration >= iterations)
  9288. break;
  9289. fn(iteration);
  9290. if (breakFunction && breakFunction()) {
  9291. loop.breakLoop();
  9292. break;
  9293. }
  9294. }
  9295. loop.executeNext();
  9296. }, timeout);
  9297. }
  9298. }, callback);
  9299. };
  9300. return AsyncLoop;
  9301. }());
  9302. BABYLON.AsyncLoop = AsyncLoop;
  9303. })(BABYLON || (BABYLON = {}));
  9304. //# sourceMappingURL=babylon.tools.js.map
  9305. var BABYLON;
  9306. (function (BABYLON) {
  9307. var PromiseStates;
  9308. (function (PromiseStates) {
  9309. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9310. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9311. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9312. })(PromiseStates || (PromiseStates = {}));
  9313. var FulFillmentAgregator = /** @class */ (function () {
  9314. function FulFillmentAgregator() {
  9315. this.count = 0;
  9316. this.target = 0;
  9317. this.results = [];
  9318. }
  9319. return FulFillmentAgregator;
  9320. }());
  9321. var InternalPromise = /** @class */ (function () {
  9322. function InternalPromise(resolver) {
  9323. var _this = this;
  9324. this._state = PromiseStates.Pending;
  9325. this._children = new Array();
  9326. this._rejectWasConsumed = false;
  9327. if (!resolver) {
  9328. return;
  9329. }
  9330. try {
  9331. resolver(function (value) {
  9332. _this._resolve(value);
  9333. }, function (reason) {
  9334. _this._reject(reason);
  9335. });
  9336. }
  9337. catch (e) {
  9338. this._reject(e);
  9339. }
  9340. }
  9341. InternalPromise.prototype.catch = function (onRejected) {
  9342. return this.then(undefined, onRejected);
  9343. };
  9344. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9345. var _this = this;
  9346. var newPromise = new InternalPromise();
  9347. newPromise._onFulfilled = onFulfilled;
  9348. newPromise._onRejected = onRejected;
  9349. // Composition
  9350. this._children.push(newPromise);
  9351. if (this._state !== PromiseStates.Pending) {
  9352. BABYLON.Tools.SetImmediate(function () {
  9353. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9354. var returnedValue = newPromise._resolve(_this._result);
  9355. if (returnedValue !== undefined && returnedValue !== null) {
  9356. if (returnedValue._state !== undefined) {
  9357. var returnedPromise = returnedValue;
  9358. newPromise._children.push(returnedPromise);
  9359. newPromise = returnedPromise;
  9360. }
  9361. else {
  9362. newPromise._result = returnedValue;
  9363. }
  9364. }
  9365. }
  9366. else {
  9367. newPromise._reject(_this._reason);
  9368. }
  9369. });
  9370. }
  9371. return newPromise;
  9372. };
  9373. InternalPromise.prototype._moveChildren = function (children) {
  9374. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9375. if (this._state === PromiseStates.Fulfilled) {
  9376. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9377. var child = _b[_i];
  9378. child._resolve(this._result);
  9379. }
  9380. }
  9381. else if (this._state === PromiseStates.Rejected) {
  9382. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9383. var child = _d[_c];
  9384. child._reject(this._reason);
  9385. }
  9386. }
  9387. var _a;
  9388. };
  9389. InternalPromise.prototype._resolve = function (value) {
  9390. try {
  9391. this._state = PromiseStates.Fulfilled;
  9392. this._result = value;
  9393. var returnedValue = null;
  9394. if (this._onFulfilled) {
  9395. returnedValue = this._onFulfilled(value);
  9396. }
  9397. if (returnedValue !== undefined && returnedValue !== null) {
  9398. if (returnedValue._state !== undefined) {
  9399. // Transmit children
  9400. var returnedPromise = returnedValue;
  9401. returnedPromise._moveChildren(this._children);
  9402. }
  9403. else {
  9404. value = returnedValue;
  9405. }
  9406. }
  9407. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9408. var child = _a[_i];
  9409. child._resolve(value);
  9410. }
  9411. this._children.length = 0;
  9412. delete this._onFulfilled;
  9413. delete this._onRejected;
  9414. return returnedValue;
  9415. }
  9416. catch (e) {
  9417. this._reject(e, true);
  9418. }
  9419. return null;
  9420. };
  9421. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9422. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9423. this._state = PromiseStates.Rejected;
  9424. this._reason = reason;
  9425. if (this._onRejected && !onLocalThrow) {
  9426. try {
  9427. this._onRejected(reason);
  9428. this._rejectWasConsumed = true;
  9429. }
  9430. catch (e) {
  9431. reason = e;
  9432. }
  9433. }
  9434. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9435. var child = _a[_i];
  9436. if (this._rejectWasConsumed) {
  9437. child._resolve(null);
  9438. }
  9439. else {
  9440. child._reject(reason);
  9441. }
  9442. }
  9443. this._children.length = 0;
  9444. delete this._onFulfilled;
  9445. delete this._onRejected;
  9446. };
  9447. InternalPromise.resolve = function (value) {
  9448. var newPromise = new InternalPromise();
  9449. newPromise._resolve(value);
  9450. return newPromise;
  9451. };
  9452. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9453. promise.then(function (value) {
  9454. agregator.results[index] = value;
  9455. agregator.count++;
  9456. if (agregator.count === agregator.target) {
  9457. agregator.rootPromise._resolve(agregator.results);
  9458. }
  9459. return null;
  9460. }, function (reason) {
  9461. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9462. agregator.rootPromise._reject(reason);
  9463. }
  9464. });
  9465. };
  9466. InternalPromise.all = function (promises) {
  9467. var newPromise = new InternalPromise();
  9468. var agregator = new FulFillmentAgregator();
  9469. agregator.target = promises.length;
  9470. agregator.rootPromise = newPromise;
  9471. if (promises.length) {
  9472. for (var index = 0; index < promises.length; index++) {
  9473. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9474. }
  9475. }
  9476. else {
  9477. newPromise._resolve([]);
  9478. }
  9479. return newPromise;
  9480. };
  9481. return InternalPromise;
  9482. }());
  9483. /**
  9484. * Helper class that provides a small promise polyfill
  9485. */
  9486. var PromisePolyfill = /** @class */ (function () {
  9487. function PromisePolyfill() {
  9488. }
  9489. /**
  9490. * Static function used to check if the polyfill is required
  9491. * If this is the case then the function will inject the polyfill to window.Promise
  9492. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9493. */
  9494. PromisePolyfill.Apply = function (force) {
  9495. if (force === void 0) { force = false; }
  9496. if (force || typeof Promise === 'undefined') {
  9497. var root = window;
  9498. root.Promise = InternalPromise;
  9499. }
  9500. };
  9501. return PromisePolyfill;
  9502. }());
  9503. BABYLON.PromisePolyfill = PromisePolyfill;
  9504. })(BABYLON || (BABYLON = {}));
  9505. //# sourceMappingURL=babylon.promise.js.map
  9506. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9507. var BABYLON;
  9508. (function (BABYLON) {
  9509. /**
  9510. * Helper class to push actions to a pool of workers.
  9511. */
  9512. var WorkerPool = /** @class */ (function () {
  9513. /**
  9514. * Constructor
  9515. * @param workers Array of workers to use for actions
  9516. */
  9517. function WorkerPool(workers) {
  9518. this._pendingActions = new Array();
  9519. this._workerInfos = workers.map(function (worker) { return ({
  9520. worker: worker,
  9521. active: false
  9522. }); });
  9523. }
  9524. /**
  9525. * Terminates all workers and clears any pending actions.
  9526. */
  9527. WorkerPool.prototype.dispose = function () {
  9528. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9529. var workerInfo = _a[_i];
  9530. workerInfo.worker.terminate();
  9531. }
  9532. delete this._workerInfos;
  9533. delete this._pendingActions;
  9534. };
  9535. /**
  9536. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9537. * pended until a worker has completed its action.
  9538. * @param action The action to perform. Call onComplete when the action is complete.
  9539. */
  9540. WorkerPool.prototype.push = function (action) {
  9541. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9542. var workerInfo = _a[_i];
  9543. if (!workerInfo.active) {
  9544. this._execute(workerInfo, action);
  9545. return;
  9546. }
  9547. }
  9548. this._pendingActions.push(action);
  9549. };
  9550. WorkerPool.prototype._execute = function (workerInfo, action) {
  9551. var _this = this;
  9552. workerInfo.active = true;
  9553. action(workerInfo.worker, function () {
  9554. workerInfo.active = false;
  9555. var nextAction = _this._pendingActions.shift();
  9556. if (nextAction) {
  9557. _this._execute(workerInfo, nextAction);
  9558. }
  9559. });
  9560. };
  9561. return WorkerPool;
  9562. }());
  9563. BABYLON.WorkerPool = WorkerPool;
  9564. })(BABYLON || (BABYLON = {}));
  9565. //# sourceMappingURL=babylon.workerPool.js.map
  9566. var BABYLON;
  9567. (function (BABYLON) {
  9568. var _AlphaState = /** @class */ (function () {
  9569. /**
  9570. * Initializes the state.
  9571. */
  9572. function _AlphaState() {
  9573. this._isAlphaBlendDirty = false;
  9574. this._isBlendFunctionParametersDirty = false;
  9575. this._isBlendEquationParametersDirty = false;
  9576. this._isBlendConstantsDirty = false;
  9577. this._alphaBlend = false;
  9578. this._blendFunctionParameters = new Array(4);
  9579. this._blendEquationParameters = new Array(2);
  9580. this._blendConstants = new Array(4);
  9581. this.reset();
  9582. }
  9583. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9584. get: function () {
  9585. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9591. get: function () {
  9592. return this._alphaBlend;
  9593. },
  9594. set: function (value) {
  9595. if (this._alphaBlend === value) {
  9596. return;
  9597. }
  9598. this._alphaBlend = value;
  9599. this._isAlphaBlendDirty = true;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9605. if (this._blendConstants[0] === r &&
  9606. this._blendConstants[1] === g &&
  9607. this._blendConstants[2] === b &&
  9608. this._blendConstants[3] === a) {
  9609. return;
  9610. }
  9611. this._blendConstants[0] = r;
  9612. this._blendConstants[1] = g;
  9613. this._blendConstants[2] = b;
  9614. this._blendConstants[3] = a;
  9615. this._isBlendConstantsDirty = true;
  9616. };
  9617. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9618. if (this._blendFunctionParameters[0] === value0 &&
  9619. this._blendFunctionParameters[1] === value1 &&
  9620. this._blendFunctionParameters[2] === value2 &&
  9621. this._blendFunctionParameters[3] === value3) {
  9622. return;
  9623. }
  9624. this._blendFunctionParameters[0] = value0;
  9625. this._blendFunctionParameters[1] = value1;
  9626. this._blendFunctionParameters[2] = value2;
  9627. this._blendFunctionParameters[3] = value3;
  9628. this._isBlendFunctionParametersDirty = true;
  9629. };
  9630. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9631. if (this._blendEquationParameters[0] === rgb &&
  9632. this._blendEquationParameters[1] === alpha) {
  9633. return;
  9634. }
  9635. this._blendEquationParameters[0] = rgb;
  9636. this._blendEquationParameters[1] = alpha;
  9637. this._isBlendEquationParametersDirty = true;
  9638. };
  9639. _AlphaState.prototype.reset = function () {
  9640. this._alphaBlend = false;
  9641. this._blendFunctionParameters[0] = null;
  9642. this._blendFunctionParameters[1] = null;
  9643. this._blendFunctionParameters[2] = null;
  9644. this._blendFunctionParameters[3] = null;
  9645. this._blendEquationParameters[0] = null;
  9646. this._blendEquationParameters[1] = null;
  9647. this._blendConstants[0] = null;
  9648. this._blendConstants[1] = null;
  9649. this._blendConstants[2] = null;
  9650. this._blendConstants[3] = null;
  9651. this._isAlphaBlendDirty = true;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. };
  9656. _AlphaState.prototype.apply = function (gl) {
  9657. if (!this.isDirty) {
  9658. return;
  9659. }
  9660. // Alpha blend
  9661. if (this._isAlphaBlendDirty) {
  9662. if (this._alphaBlend) {
  9663. gl.enable(gl.BLEND);
  9664. }
  9665. else {
  9666. gl.disable(gl.BLEND);
  9667. }
  9668. this._isAlphaBlendDirty = false;
  9669. }
  9670. // Alpha function
  9671. if (this._isBlendFunctionParametersDirty) {
  9672. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9673. this._isBlendFunctionParametersDirty = false;
  9674. }
  9675. // Alpha equation
  9676. if (this._isBlendEquationParametersDirty) {
  9677. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9678. this._isBlendEquationParametersDirty = false;
  9679. }
  9680. // Constants
  9681. if (this._isBlendConstantsDirty) {
  9682. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9683. this._isBlendConstantsDirty = false;
  9684. }
  9685. };
  9686. return _AlphaState;
  9687. }());
  9688. BABYLON._AlphaState = _AlphaState;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var _DepthCullingState = /** @class */ (function () {
  9694. /**
  9695. * Initializes the state.
  9696. */
  9697. function _DepthCullingState() {
  9698. this._isDepthTestDirty = false;
  9699. this._isDepthMaskDirty = false;
  9700. this._isDepthFuncDirty = false;
  9701. this._isCullFaceDirty = false;
  9702. this._isCullDirty = false;
  9703. this._isZOffsetDirty = false;
  9704. this._isFrontFaceDirty = false;
  9705. this.reset();
  9706. }
  9707. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9708. get: function () {
  9709. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9715. get: function () {
  9716. return this._zOffset;
  9717. },
  9718. set: function (value) {
  9719. if (this._zOffset === value) {
  9720. return;
  9721. }
  9722. this._zOffset = value;
  9723. this._isZOffsetDirty = true;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9729. get: function () {
  9730. return this._cullFace;
  9731. },
  9732. set: function (value) {
  9733. if (this._cullFace === value) {
  9734. return;
  9735. }
  9736. this._cullFace = value;
  9737. this._isCullFaceDirty = true;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9743. get: function () {
  9744. return this._cull;
  9745. },
  9746. set: function (value) {
  9747. if (this._cull === value) {
  9748. return;
  9749. }
  9750. this._cull = value;
  9751. this._isCullDirty = true;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9757. get: function () {
  9758. return this._depthFunc;
  9759. },
  9760. set: function (value) {
  9761. if (this._depthFunc === value) {
  9762. return;
  9763. }
  9764. this._depthFunc = value;
  9765. this._isDepthFuncDirty = true;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9771. get: function () {
  9772. return this._depthMask;
  9773. },
  9774. set: function (value) {
  9775. if (this._depthMask === value) {
  9776. return;
  9777. }
  9778. this._depthMask = value;
  9779. this._isDepthMaskDirty = true;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9785. get: function () {
  9786. return this._depthTest;
  9787. },
  9788. set: function (value) {
  9789. if (this._depthTest === value) {
  9790. return;
  9791. }
  9792. this._depthTest = value;
  9793. this._isDepthTestDirty = true;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9799. get: function () {
  9800. return this._frontFace;
  9801. },
  9802. set: function (value) {
  9803. if (this._frontFace === value) {
  9804. return;
  9805. }
  9806. this._frontFace = value;
  9807. this._isFrontFaceDirty = true;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. _DepthCullingState.prototype.reset = function () {
  9813. this._depthMask = true;
  9814. this._depthTest = true;
  9815. this._depthFunc = null;
  9816. this._cullFace = null;
  9817. this._cull = null;
  9818. this._zOffset = 0;
  9819. this._frontFace = null;
  9820. this._isDepthTestDirty = true;
  9821. this._isDepthMaskDirty = true;
  9822. this._isDepthFuncDirty = false;
  9823. this._isCullFaceDirty = false;
  9824. this._isCullDirty = false;
  9825. this._isZOffsetDirty = false;
  9826. this._isFrontFaceDirty = false;
  9827. };
  9828. _DepthCullingState.prototype.apply = function (gl) {
  9829. if (!this.isDirty) {
  9830. return;
  9831. }
  9832. // Cull
  9833. if (this._isCullDirty) {
  9834. if (this.cull) {
  9835. gl.enable(gl.CULL_FACE);
  9836. }
  9837. else {
  9838. gl.disable(gl.CULL_FACE);
  9839. }
  9840. this._isCullDirty = false;
  9841. }
  9842. // Cull face
  9843. if (this._isCullFaceDirty) {
  9844. gl.cullFace(this.cullFace);
  9845. this._isCullFaceDirty = false;
  9846. }
  9847. // Depth mask
  9848. if (this._isDepthMaskDirty) {
  9849. gl.depthMask(this.depthMask);
  9850. this._isDepthMaskDirty = false;
  9851. }
  9852. // Depth test
  9853. if (this._isDepthTestDirty) {
  9854. if (this.depthTest) {
  9855. gl.enable(gl.DEPTH_TEST);
  9856. }
  9857. else {
  9858. gl.disable(gl.DEPTH_TEST);
  9859. }
  9860. this._isDepthTestDirty = false;
  9861. }
  9862. // Depth func
  9863. if (this._isDepthFuncDirty) {
  9864. gl.depthFunc(this.depthFunc);
  9865. this._isDepthFuncDirty = false;
  9866. }
  9867. // zOffset
  9868. if (this._isZOffsetDirty) {
  9869. if (this.zOffset) {
  9870. gl.enable(gl.POLYGON_OFFSET_FILL);
  9871. gl.polygonOffset(this.zOffset, 0);
  9872. }
  9873. else {
  9874. gl.disable(gl.POLYGON_OFFSET_FILL);
  9875. }
  9876. this._isZOffsetDirty = false;
  9877. }
  9878. // Front face
  9879. if (this._isFrontFaceDirty) {
  9880. gl.frontFace(this.frontFace);
  9881. this._isFrontFaceDirty = false;
  9882. }
  9883. };
  9884. return _DepthCullingState;
  9885. }());
  9886. BABYLON._DepthCullingState = _DepthCullingState;
  9887. })(BABYLON || (BABYLON = {}));
  9888. //# sourceMappingURL=babylon.depthCullingState.js.map
  9889. var BABYLON;
  9890. (function (BABYLON) {
  9891. var _StencilState = /** @class */ (function () {
  9892. function _StencilState() {
  9893. this._isStencilTestDirty = false;
  9894. this._isStencilMaskDirty = false;
  9895. this._isStencilFuncDirty = false;
  9896. this._isStencilOpDirty = false;
  9897. this.reset();
  9898. }
  9899. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9900. get: function () {
  9901. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9907. get: function () {
  9908. return this._stencilFunc;
  9909. },
  9910. set: function (value) {
  9911. if (this._stencilFunc === value) {
  9912. return;
  9913. }
  9914. this._stencilFunc = value;
  9915. this._isStencilFuncDirty = true;
  9916. },
  9917. enumerable: true,
  9918. configurable: true
  9919. });
  9920. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9921. get: function () {
  9922. return this._stencilFuncRef;
  9923. },
  9924. set: function (value) {
  9925. if (this._stencilFuncRef === value) {
  9926. return;
  9927. }
  9928. this._stencilFuncRef = value;
  9929. this._isStencilFuncDirty = true;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9935. get: function () {
  9936. return this._stencilFuncMask;
  9937. },
  9938. set: function (value) {
  9939. if (this._stencilFuncMask === value) {
  9940. return;
  9941. }
  9942. this._stencilFuncMask = value;
  9943. this._isStencilFuncDirty = true;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9949. get: function () {
  9950. return this._stencilOpStencilFail;
  9951. },
  9952. set: function (value) {
  9953. if (this._stencilOpStencilFail === value) {
  9954. return;
  9955. }
  9956. this._stencilOpStencilFail = value;
  9957. this._isStencilOpDirty = true;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9963. get: function () {
  9964. return this._stencilOpDepthFail;
  9965. },
  9966. set: function (value) {
  9967. if (this._stencilOpDepthFail === value) {
  9968. return;
  9969. }
  9970. this._stencilOpDepthFail = value;
  9971. this._isStencilOpDirty = true;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9977. get: function () {
  9978. return this._stencilOpStencilDepthPass;
  9979. },
  9980. set: function (value) {
  9981. if (this._stencilOpStencilDepthPass === value) {
  9982. return;
  9983. }
  9984. this._stencilOpStencilDepthPass = value;
  9985. this._isStencilOpDirty = true;
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9991. get: function () {
  9992. return this._stencilMask;
  9993. },
  9994. set: function (value) {
  9995. if (this._stencilMask === value) {
  9996. return;
  9997. }
  9998. this._stencilMask = value;
  9999. this._isStencilMaskDirty = true;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10005. get: function () {
  10006. return this._stencilTest;
  10007. },
  10008. set: function (value) {
  10009. if (this._stencilTest === value) {
  10010. return;
  10011. }
  10012. this._stencilTest = value;
  10013. this._isStencilTestDirty = true;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. _StencilState.prototype.reset = function () {
  10019. this._stencilTest = false;
  10020. this._stencilMask = 0xFF;
  10021. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10022. this._stencilFuncRef = 1;
  10023. this._stencilFuncMask = 0xFF;
  10024. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10025. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10026. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10027. this._isStencilTestDirty = true;
  10028. this._isStencilMaskDirty = true;
  10029. this._isStencilFuncDirty = true;
  10030. this._isStencilOpDirty = true;
  10031. };
  10032. _StencilState.prototype.apply = function (gl) {
  10033. if (!this.isDirty) {
  10034. return;
  10035. }
  10036. // Stencil test
  10037. if (this._isStencilTestDirty) {
  10038. if (this.stencilTest) {
  10039. gl.enable(gl.STENCIL_TEST);
  10040. }
  10041. else {
  10042. gl.disable(gl.STENCIL_TEST);
  10043. }
  10044. this._isStencilTestDirty = false;
  10045. }
  10046. // Stencil mask
  10047. if (this._isStencilMaskDirty) {
  10048. gl.stencilMask(this.stencilMask);
  10049. this._isStencilMaskDirty = false;
  10050. }
  10051. // Stencil func
  10052. if (this._isStencilFuncDirty) {
  10053. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10054. this._isStencilFuncDirty = false;
  10055. }
  10056. // Stencil op
  10057. if (this._isStencilOpDirty) {
  10058. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10059. this._isStencilOpDirty = false;
  10060. }
  10061. };
  10062. return _StencilState;
  10063. }());
  10064. BABYLON._StencilState = _StencilState;
  10065. })(BABYLON || (BABYLON = {}));
  10066. //# sourceMappingURL=babylon.stencilState.js.map
  10067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10069. s = arguments[i];
  10070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10071. t[p] = s[p];
  10072. }
  10073. return t;
  10074. };
  10075. var BABYLON;
  10076. (function (BABYLON) {
  10077. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10078. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10079. };
  10080. var compileRawShader = function (gl, source, type) {
  10081. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10082. gl.shaderSource(shader, source);
  10083. gl.compileShader(shader);
  10084. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10085. var log = gl.getShaderInfoLog(shader);
  10086. if (log) {
  10087. throw new Error(log);
  10088. }
  10089. }
  10090. if (!shader) {
  10091. throw new Error("Something went wrong while compile the shader.");
  10092. }
  10093. return shader;
  10094. };
  10095. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10096. var magFilter = gl.NEAREST;
  10097. var minFilter = gl.NEAREST;
  10098. switch (samplingMode) {
  10099. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10100. magFilter = gl.LINEAR;
  10101. if (generateMipMaps) {
  10102. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10103. }
  10104. else {
  10105. minFilter = gl.LINEAR;
  10106. }
  10107. break;
  10108. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10109. magFilter = gl.LINEAR;
  10110. if (generateMipMaps) {
  10111. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10112. }
  10113. else {
  10114. minFilter = gl.LINEAR;
  10115. }
  10116. break;
  10117. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10118. magFilter = gl.NEAREST;
  10119. if (generateMipMaps) {
  10120. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10121. }
  10122. else {
  10123. minFilter = gl.NEAREST;
  10124. }
  10125. break;
  10126. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10127. magFilter = gl.NEAREST;
  10128. if (generateMipMaps) {
  10129. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10130. }
  10131. else {
  10132. minFilter = gl.NEAREST;
  10133. }
  10134. break;
  10135. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10136. magFilter = gl.NEAREST;
  10137. if (generateMipMaps) {
  10138. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10139. }
  10140. else {
  10141. minFilter = gl.LINEAR;
  10142. }
  10143. break;
  10144. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10145. magFilter = gl.NEAREST;
  10146. if (generateMipMaps) {
  10147. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10148. }
  10149. else {
  10150. minFilter = gl.LINEAR;
  10151. }
  10152. break;
  10153. case BABYLON.Texture.NEAREST_LINEAR:
  10154. magFilter = gl.NEAREST;
  10155. minFilter = gl.LINEAR;
  10156. break;
  10157. case BABYLON.Texture.NEAREST_NEAREST:
  10158. magFilter = gl.NEAREST;
  10159. minFilter = gl.NEAREST;
  10160. break;
  10161. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10162. magFilter = gl.LINEAR;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10165. }
  10166. else {
  10167. minFilter = gl.NEAREST;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10171. magFilter = gl.LINEAR;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10174. }
  10175. else {
  10176. minFilter = gl.NEAREST;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.LINEAR_LINEAR:
  10180. magFilter = gl.LINEAR;
  10181. minFilter = gl.LINEAR;
  10182. break;
  10183. case BABYLON.Texture.LINEAR_NEAREST:
  10184. magFilter = gl.LINEAR;
  10185. minFilter = gl.NEAREST;
  10186. break;
  10187. }
  10188. return {
  10189. min: minFilter,
  10190. mag: magFilter
  10191. };
  10192. };
  10193. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10194. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10195. var img;
  10196. var onload = function () {
  10197. loadedImages[index] = img;
  10198. loadedImages._internalCount++;
  10199. if (scene) {
  10200. scene._removePendingData(img);
  10201. }
  10202. if (loadedImages._internalCount === 6) {
  10203. onfinish(loadedImages);
  10204. }
  10205. };
  10206. var onerror = function (message, exception) {
  10207. if (scene) {
  10208. scene._removePendingData(img);
  10209. }
  10210. if (onErrorCallBack) {
  10211. onErrorCallBack(message, exception);
  10212. }
  10213. };
  10214. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10215. if (scene) {
  10216. scene._addPendingData(img);
  10217. }
  10218. };
  10219. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10220. if (onError === void 0) { onError = null; }
  10221. var loadedImages = [];
  10222. loadedImages._internalCount = 0;
  10223. for (var index = 0; index < 6; index++) {
  10224. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10225. }
  10226. };
  10227. var BufferPointer = /** @class */ (function () {
  10228. function BufferPointer() {
  10229. }
  10230. return BufferPointer;
  10231. }());
  10232. var InstancingAttributeInfo = /** @class */ (function () {
  10233. function InstancingAttributeInfo() {
  10234. }
  10235. return InstancingAttributeInfo;
  10236. }());
  10237. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10238. /**
  10239. * Define options used to create a render target texture
  10240. */
  10241. var RenderTargetCreationOptions = /** @class */ (function () {
  10242. function RenderTargetCreationOptions() {
  10243. }
  10244. return RenderTargetCreationOptions;
  10245. }());
  10246. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10247. /**
  10248. * Define options used to create a depth texture
  10249. */
  10250. var DepthTextureCreationOptions = /** @class */ (function () {
  10251. function DepthTextureCreationOptions() {
  10252. }
  10253. return DepthTextureCreationOptions;
  10254. }());
  10255. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10256. /**
  10257. * Regroup several parameters relative to the browser in use
  10258. */
  10259. var EngineCapabilities = /** @class */ (function () {
  10260. function EngineCapabilities() {
  10261. }
  10262. return EngineCapabilities;
  10263. }());
  10264. BABYLON.EngineCapabilities = EngineCapabilities;
  10265. /**
  10266. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10267. */
  10268. var Engine = /** @class */ (function () {
  10269. /**
  10270. * @constructor
  10271. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10272. * @param antialias defines enable antialiasing (default: false)
  10273. * @param options defines further options to be sent to the getContext() function
  10274. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10275. */
  10276. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10277. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10278. var _this = this;
  10279. // Public members
  10280. this.forcePOTTextures = false;
  10281. this.isFullscreen = false;
  10282. this.isPointerLock = false;
  10283. this.cullBackFaces = true;
  10284. this.renderEvenInBackground = true;
  10285. this.preventCacheWipeBetweenFrames = false;
  10286. // To enable/disable IDB support and avoid XHR on .manifest
  10287. this.enableOfflineSupport = false;
  10288. this.scenes = new Array();
  10289. this.postProcesses = new Array();
  10290. // Observables
  10291. /**
  10292. * Observable event triggered each time the rendering canvas is resized
  10293. */
  10294. this.onResizeObservable = new BABYLON.Observable();
  10295. /**
  10296. * Observable event triggered each time the canvas loses focus
  10297. */
  10298. this.onCanvasBlurObservable = new BABYLON.Observable();
  10299. /**
  10300. * Observable event triggered each time the canvas gains focus
  10301. */
  10302. this.onCanvasFocusObservable = new BABYLON.Observable();
  10303. /**
  10304. * Observable event triggered each time the canvas receives pointerout event
  10305. */
  10306. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10307. /**
  10308. * Observable event triggered before each texture is initialized
  10309. */
  10310. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10311. //WebVR
  10312. this._vrDisplay = undefined;
  10313. this._vrSupported = false;
  10314. this._vrExclusivePointerMode = false;
  10315. // Uniform buffers list
  10316. this.disableUniformBuffers = false;
  10317. this._uniformBuffers = new Array();
  10318. // Observables
  10319. /**
  10320. * Observable raised when the engine begins a new frame
  10321. */
  10322. this.onBeginFrameObservable = new BABYLON.Observable();
  10323. /**
  10324. * Observable raised when the engine ends the current frame
  10325. */
  10326. this.onEndFrameObservable = new BABYLON.Observable();
  10327. /**
  10328. * Observable raised when the engine is about to compile a shader
  10329. */
  10330. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10331. /**
  10332. * Observable raised when the engine has jsut compiled a shader
  10333. */
  10334. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10335. this._windowIsBackground = false;
  10336. this._webGLVersion = 1.0;
  10337. this._badOS = false;
  10338. this._badDesktopOS = false;
  10339. /**
  10340. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10341. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10342. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10343. */
  10344. this.disableTextureBindingOptimization = false;
  10345. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10346. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10347. this.onVRRequestPresentStart = new BABYLON.Observable();
  10348. this._colorWrite = true;
  10349. this._drawCalls = new BABYLON.PerfCounter();
  10350. this._textureCollisions = new BABYLON.PerfCounter();
  10351. this._renderingQueueLaunched = false;
  10352. this._activeRenderLoops = new Array();
  10353. // Deterministic lockstepMaxSteps
  10354. this._deterministicLockstep = false;
  10355. this._lockstepMaxSteps = 4;
  10356. // Lost context
  10357. this.onContextLostObservable = new BABYLON.Observable();
  10358. this.onContextRestoredObservable = new BABYLON.Observable();
  10359. this._contextWasLost = false;
  10360. this._doNotHandleContextLost = false;
  10361. // FPS
  10362. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10363. this._fps = 60;
  10364. this._deltaTime = 0;
  10365. /**
  10366. * Turn this value on if you want to pause FPS computation when in background
  10367. */
  10368. this.disablePerformanceMonitorInBackground = false;
  10369. // States
  10370. this._depthCullingState = new BABYLON._DepthCullingState();
  10371. this._stencilState = new BABYLON._StencilState();
  10372. this._alphaState = new BABYLON._AlphaState();
  10373. this._alphaMode = Engine.ALPHA_DISABLE;
  10374. // Cache
  10375. this._internalTexturesCache = new Array();
  10376. this._activeChannel = 0;
  10377. this._currentTextureChannel = -1;
  10378. this._boundTexturesCache = {};
  10379. this._compiledEffects = {};
  10380. this._vertexAttribArraysEnabled = [];
  10381. this._uintIndicesCurrentlySet = false;
  10382. this._currentBoundBuffer = new Array();
  10383. this._currentBufferPointers = new Array();
  10384. this._currentInstanceLocations = new Array();
  10385. this._currentInstanceBuffers = new Array();
  10386. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10387. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10388. this._vaoRecordInProgress = false;
  10389. this._mustWipeVertexAttributes = false;
  10390. this._nextFreeTextureSlots = new Array();
  10391. this._maxSimultaneousTextures = 0;
  10392. this._activeRequests = new Array();
  10393. // Hardware supported Compressed Textures
  10394. this._texturesSupported = new Array();
  10395. this._onVRFullScreenTriggered = function () {
  10396. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10397. //get the old size before we change
  10398. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10399. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10400. //get the width and height, change the render size
  10401. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10402. _this.setHardwareScalingLevel(1);
  10403. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10404. }
  10405. else {
  10406. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10407. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10408. }
  10409. };
  10410. this._boundUniforms = {};
  10411. // Register promises
  10412. BABYLON.PromisePolyfill.Apply();
  10413. var canvas = null;
  10414. Engine.Instances.push(this);
  10415. if (!canvasOrContext) {
  10416. return;
  10417. }
  10418. options = options || {};
  10419. if (canvasOrContext.getContext) {
  10420. canvas = canvasOrContext;
  10421. this._renderingCanvas = canvas;
  10422. if (antialias != null) {
  10423. options.antialias = antialias;
  10424. }
  10425. if (options.deterministicLockstep === undefined) {
  10426. options.deterministicLockstep = false;
  10427. }
  10428. if (options.lockstepMaxSteps === undefined) {
  10429. options.lockstepMaxSteps = 4;
  10430. }
  10431. if (options.preserveDrawingBuffer === undefined) {
  10432. options.preserveDrawingBuffer = false;
  10433. }
  10434. if (options.audioEngine === undefined) {
  10435. options.audioEngine = true;
  10436. }
  10437. if (options.stencil === undefined) {
  10438. options.stencil = true;
  10439. }
  10440. this._deterministicLockstep = options.deterministicLockstep;
  10441. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10442. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10443. // Exceptions
  10444. if (navigator && navigator.userAgent) {
  10445. var ua = navigator.userAgent;
  10446. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10447. var exception = _a[_i];
  10448. var key = exception.key;
  10449. var targets = exception.targets;
  10450. if (ua.indexOf(key) > -1) {
  10451. if (exception.capture && exception.captureConstraint) {
  10452. var capture = exception.capture;
  10453. var constraint = exception.captureConstraint;
  10454. var regex = new RegExp(capture);
  10455. var matches = regex.exec(ua);
  10456. if (matches && matches.length > 0) {
  10457. var capturedValue = parseInt(matches[matches.length - 1]);
  10458. if (capturedValue >= constraint) {
  10459. continue;
  10460. }
  10461. }
  10462. }
  10463. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10464. var target = targets_1[_b];
  10465. switch (target) {
  10466. case "uniformBuffer":
  10467. this.disableUniformBuffers = true;
  10468. break;
  10469. case "textureBindingOptimization":
  10470. this.disableTextureBindingOptimization = true;
  10471. break;
  10472. }
  10473. }
  10474. break;
  10475. }
  10476. }
  10477. }
  10478. // GL
  10479. if (!options.disableWebGL2Support) {
  10480. try {
  10481. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10482. if (this._gl) {
  10483. this._webGLVersion = 2.0;
  10484. }
  10485. }
  10486. catch (e) {
  10487. // Do nothing
  10488. }
  10489. }
  10490. if (!this._gl) {
  10491. if (!canvas) {
  10492. throw new Error("The provided canvas is null or undefined.");
  10493. }
  10494. try {
  10495. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10496. }
  10497. catch (e) {
  10498. throw new Error("WebGL not supported");
  10499. }
  10500. }
  10501. if (!this._gl) {
  10502. throw new Error("WebGL not supported");
  10503. }
  10504. this._onCanvasFocus = function () {
  10505. _this.onCanvasFocusObservable.notifyObservers(_this);
  10506. };
  10507. this._onCanvasBlur = function () {
  10508. _this.onCanvasBlurObservable.notifyObservers(_this);
  10509. };
  10510. canvas.addEventListener("focus", this._onCanvasFocus);
  10511. canvas.addEventListener("blur", this._onCanvasBlur);
  10512. this._onBlur = function () {
  10513. if (_this.disablePerformanceMonitorInBackground) {
  10514. _this._performanceMonitor.disable();
  10515. }
  10516. _this._windowIsBackground = true;
  10517. };
  10518. this._onFocus = function () {
  10519. if (_this.disablePerformanceMonitorInBackground) {
  10520. _this._performanceMonitor.enable();
  10521. }
  10522. _this._windowIsBackground = false;
  10523. };
  10524. this._onCanvasPointerOut = function (ev) {
  10525. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10526. };
  10527. window.addEventListener("blur", this._onBlur);
  10528. window.addEventListener("focus", this._onFocus);
  10529. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10530. // Context lost
  10531. if (!this._doNotHandleContextLost) {
  10532. this._onContextLost = function (evt) {
  10533. evt.preventDefault();
  10534. _this._contextWasLost = true;
  10535. BABYLON.Tools.Warn("WebGL context lost.");
  10536. _this.onContextLostObservable.notifyObservers(_this);
  10537. };
  10538. this._onContextRestored = function (evt) {
  10539. // Adding a timeout to avoid race condition at browser level
  10540. setTimeout(function () {
  10541. // Rebuild gl context
  10542. _this._initGLContext();
  10543. // Rebuild effects
  10544. _this._rebuildEffects();
  10545. // Rebuild textures
  10546. _this._rebuildInternalTextures();
  10547. // Rebuild buffers
  10548. _this._rebuildBuffers();
  10549. // Cache
  10550. _this.wipeCaches(true);
  10551. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10552. _this.onContextRestoredObservable.notifyObservers(_this);
  10553. _this._contextWasLost = false;
  10554. }, 0);
  10555. };
  10556. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10557. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10558. }
  10559. }
  10560. else {
  10561. this._gl = canvasOrContext;
  10562. this._renderingCanvas = this._gl.canvas;
  10563. if (this._gl.renderbufferStorageMultisample) {
  10564. this._webGLVersion = 2.0;
  10565. }
  10566. options.stencil = this._gl.getContextAttributes().stencil;
  10567. }
  10568. // Viewport
  10569. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10570. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10571. this.resize();
  10572. this._isStencilEnable = options.stencil ? true : false;
  10573. this._initGLContext();
  10574. if (canvas) {
  10575. // Fullscreen
  10576. this._onFullscreenChange = function () {
  10577. if (document.fullscreen !== undefined) {
  10578. _this.isFullscreen = document.fullscreen;
  10579. }
  10580. else if (document.mozFullScreen !== undefined) {
  10581. _this.isFullscreen = document.mozFullScreen;
  10582. }
  10583. else if (document.webkitIsFullScreen !== undefined) {
  10584. _this.isFullscreen = document.webkitIsFullScreen;
  10585. }
  10586. else if (document.msIsFullScreen !== undefined) {
  10587. _this.isFullscreen = document.msIsFullScreen;
  10588. }
  10589. // Pointer lock
  10590. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10591. canvas.requestPointerLock = canvas.requestPointerLock ||
  10592. canvas.msRequestPointerLock ||
  10593. canvas.mozRequestPointerLock ||
  10594. canvas.webkitRequestPointerLock;
  10595. if (canvas.requestPointerLock) {
  10596. canvas.requestPointerLock();
  10597. }
  10598. }
  10599. };
  10600. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10601. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10602. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10603. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10604. // Pointer lock
  10605. this._onPointerLockChange = function () {
  10606. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10607. document.webkitPointerLockElement === canvas ||
  10608. document.msPointerLockElement === canvas ||
  10609. document.pointerLockElement === canvas);
  10610. };
  10611. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10612. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10613. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10614. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10615. this._onVRDisplayPointerRestricted = function () {
  10616. if (canvas) {
  10617. canvas.requestPointerLock();
  10618. }
  10619. };
  10620. this._onVRDisplayPointerUnrestricted = function () {
  10621. document.exitPointerLock();
  10622. };
  10623. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10624. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10625. }
  10626. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10627. Engine.audioEngine = new BABYLON.AudioEngine();
  10628. }
  10629. // Prepare buffer pointers
  10630. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10631. this._currentBufferPointers[i] = new BufferPointer();
  10632. }
  10633. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10634. // Load WebVR Devices
  10635. if (options.autoEnableWebVR) {
  10636. this.initWebVR();
  10637. }
  10638. // Detect if we are running on a faulty buggy OS.
  10639. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10640. // Detect if we are running on a faulty buggy desktop OS.
  10641. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10642. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10643. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10644. }
  10645. Object.defineProperty(Engine, "LastCreatedEngine", {
  10646. get: function () {
  10647. if (Engine.Instances.length === 0) {
  10648. return null;
  10649. }
  10650. return Engine.Instances[Engine.Instances.length - 1];
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "LastCreatedScene", {
  10656. get: function () {
  10657. var lastCreatedEngine = Engine.LastCreatedEngine;
  10658. if (!lastCreatedEngine) {
  10659. return null;
  10660. }
  10661. if (lastCreatedEngine.scenes.length === 0) {
  10662. return null;
  10663. }
  10664. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. /**
  10670. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10671. */
  10672. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10673. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10674. var engine = Engine.Instances[engineIndex];
  10675. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10676. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10677. }
  10678. }
  10679. };
  10680. Object.defineProperty(Engine, "NEVER", {
  10681. get: function () {
  10682. return Engine._NEVER;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(Engine, "ALWAYS", {
  10688. get: function () {
  10689. return Engine._ALWAYS;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(Engine, "LESS", {
  10695. get: function () {
  10696. return Engine._LESS;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(Engine, "EQUAL", {
  10702. get: function () {
  10703. return Engine._EQUAL;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(Engine, "LEQUAL", {
  10709. get: function () {
  10710. return Engine._LEQUAL;
  10711. },
  10712. enumerable: true,
  10713. configurable: true
  10714. });
  10715. Object.defineProperty(Engine, "GREATER", {
  10716. get: function () {
  10717. return Engine._GREATER;
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(Engine, "GEQUAL", {
  10723. get: function () {
  10724. return Engine._GEQUAL;
  10725. },
  10726. enumerable: true,
  10727. configurable: true
  10728. });
  10729. Object.defineProperty(Engine, "NOTEQUAL", {
  10730. get: function () {
  10731. return Engine._NOTEQUAL;
  10732. },
  10733. enumerable: true,
  10734. configurable: true
  10735. });
  10736. Object.defineProperty(Engine, "KEEP", {
  10737. get: function () {
  10738. return Engine._KEEP;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Engine, "REPLACE", {
  10744. get: function () {
  10745. return Engine._REPLACE;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Engine, "INCR", {
  10751. get: function () {
  10752. return Engine._INCR;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Engine, "DECR", {
  10758. get: function () {
  10759. return Engine._DECR;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "INVERT", {
  10765. get: function () {
  10766. return Engine._INVERT;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "INCR_WRAP", {
  10772. get: function () {
  10773. return Engine._INCR_WRAP;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "DECR_WRAP", {
  10779. get: function () {
  10780. return Engine._DECR_WRAP;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10786. get: function () {
  10787. return Engine._ALPHA_DISABLE;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10793. get: function () {
  10794. return Engine._ALPHA_ONEONE;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "ALPHA_ADD", {
  10800. get: function () {
  10801. return Engine._ALPHA_ADD;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10807. get: function () {
  10808. return Engine._ALPHA_COMBINE;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10814. get: function () {
  10815. return Engine._ALPHA_SUBTRACT;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10821. get: function () {
  10822. return Engine._ALPHA_MULTIPLY;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10828. get: function () {
  10829. return Engine._ALPHA_MAXIMIZED;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10835. get: function () {
  10836. return Engine._ALPHA_PREMULTIPLIED;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10842. get: function () {
  10843. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10849. get: function () {
  10850. return Engine._ALPHA_INTERPOLATE;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10856. get: function () {
  10857. return Engine._ALPHA_SCREENMODE;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10863. get: function () {
  10864. return Engine._DELAYLOADSTATE_NONE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10870. get: function () {
  10871. return Engine._DELAYLOADSTATE_LOADED;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10877. get: function () {
  10878. return Engine._DELAYLOADSTATE_LOADING;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10884. get: function () {
  10885. return Engine._DELAYLOADSTATE_NOTLOADED;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10891. get: function () {
  10892. return Engine._TEXTUREFORMAT_ALPHA;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10898. get: function () {
  10899. return Engine._TEXTUREFORMAT_LUMINANCE;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10905. /**
  10906. * R32F
  10907. */
  10908. get: function () {
  10909. return Engine._TEXTUREFORMAT_R32F;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10915. /**
  10916. * RG32F
  10917. */
  10918. get: function () {
  10919. return Engine._TEXTUREFORMAT_RG32F;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10925. /**
  10926. * RGB32F
  10927. */
  10928. get: function () {
  10929. return Engine._TEXTUREFORMAT_RGB32F;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10935. /**
  10936. * RGBA32F
  10937. */
  10938. get: function () {
  10939. return Engine._TEXTUREFORMAT_RGBA32F;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10945. get: function () {
  10946. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10952. get: function () {
  10953. return Engine._TEXTUREFORMAT_RGB;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10959. get: function () {
  10960. return Engine._TEXTUREFORMAT_RGBA;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10966. get: function () {
  10967. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10973. get: function () {
  10974. return Engine._TEXTURETYPE_FLOAT;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10980. get: function () {
  10981. return Engine._TEXTURETYPE_HALF_FLOAT;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10987. get: function () {
  10988. return Engine._SCALEMODE_FLOOR;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10994. get: function () {
  10995. return Engine._SCALEMODE_NEAREST;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11001. get: function () {
  11002. return Engine._SCALEMODE_CEILING;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "Version", {
  11008. get: function () {
  11009. return "3.2.0-alphaA";
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11015. get: function () {
  11016. return this._vrExclusivePointerMode;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11022. get: function () {
  11023. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11029. get: function () {
  11030. return this._webGLVersion < 2 || this.forcePOTTextures;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine.prototype, "badOS", {
  11036. get: function () {
  11037. return this._badOS;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11043. get: function () {
  11044. return this._badDesktopOS;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11050. get: function () {
  11051. return this._performanceMonitor;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11057. get: function () {
  11058. return this._texturesSupported;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11064. get: function () {
  11065. return this._textureFormatInUse;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine.prototype, "currentViewport", {
  11071. get: function () {
  11072. return this._cachedViewport;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11078. // Empty texture
  11079. get: function () {
  11080. if (!this._emptyTexture) {
  11081. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11082. }
  11083. return this._emptyTexture;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11089. get: function () {
  11090. if (!this._emptyTexture3D) {
  11091. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11092. }
  11093. return this._emptyTexture3D;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11099. get: function () {
  11100. if (!this._emptyCubeTexture) {
  11101. var faceData = new Uint8Array(4);
  11102. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11103. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11104. }
  11105. return this._emptyCubeTexture;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Engine.prototype._rebuildInternalTextures = function () {
  11111. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11112. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11113. var internalTexture = currentState_1[_i];
  11114. internalTexture._rebuild();
  11115. }
  11116. };
  11117. Engine.prototype._rebuildEffects = function () {
  11118. for (var key in this._compiledEffects) {
  11119. var effect = this._compiledEffects[key];
  11120. effect._prepareEffect();
  11121. }
  11122. BABYLON.Effect.ResetCache();
  11123. };
  11124. Engine.prototype._rebuildBuffers = function () {
  11125. // Index / Vertex
  11126. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11127. var scene = _a[_i];
  11128. scene.resetCachedMaterial();
  11129. scene._rebuildGeometries();
  11130. scene._rebuildTextures();
  11131. }
  11132. // Uniforms
  11133. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11134. var uniformBuffer = _c[_b];
  11135. uniformBuffer._rebuild();
  11136. }
  11137. };
  11138. Engine.prototype._initGLContext = function () {
  11139. // Caps
  11140. this._caps = new EngineCapabilities();
  11141. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11142. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11143. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11144. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11145. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11146. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11147. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11148. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11149. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11150. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11151. // Infos
  11152. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11153. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11154. if (rendererInfo != null) {
  11155. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11156. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11157. }
  11158. if (!this._glVendor) {
  11159. this._glVendor = "Unknown vendor";
  11160. }
  11161. if (!this._glRenderer) {
  11162. this._glRenderer = "Unknown renderer";
  11163. }
  11164. // Constants
  11165. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11166. if (this._gl.RGBA16F !== 0x881A) {
  11167. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11168. }
  11169. if (this._gl.RGBA32F !== 0x8814) {
  11170. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11171. }
  11172. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11173. this._gl.DEPTH24_STENCIL8 = 35056;
  11174. }
  11175. // Extensions
  11176. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11177. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11178. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11179. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11180. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11181. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11182. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11183. 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');
  11184. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11185. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11186. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11187. this._caps.highPrecisionShaderSupported = true;
  11188. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11189. if (this._caps.timerQuery) {
  11190. if (this._webGLVersion === 1) {
  11191. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11192. }
  11193. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11194. }
  11195. // Checks if some of the format renders first to allow the use of webgl inspector.
  11196. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11197. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11198. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11199. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11200. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11201. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11202. if (this._webGLVersion > 1) {
  11203. this._gl.HALF_FLOAT_OES = 0x140B;
  11204. }
  11205. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11206. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11207. // Draw buffers
  11208. if (this._webGLVersion > 1) {
  11209. this._caps.drawBuffersExtension = true;
  11210. }
  11211. else {
  11212. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11213. if (drawBuffersExtension !== null) {
  11214. this._caps.drawBuffersExtension = true;
  11215. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11216. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11217. for (var i = 0; i < 16; i++) {
  11218. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11219. }
  11220. }
  11221. else {
  11222. this._caps.drawBuffersExtension = false;
  11223. }
  11224. }
  11225. // Depth Texture
  11226. if (this._webGLVersion > 1) {
  11227. this._caps.depthTextureExtension = true;
  11228. }
  11229. else {
  11230. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11231. if (depthTextureExtension != null) {
  11232. this._caps.depthTextureExtension = true;
  11233. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11234. }
  11235. }
  11236. // Vertex array object
  11237. if (this._webGLVersion > 1) {
  11238. this._caps.vertexArrayObject = true;
  11239. }
  11240. else {
  11241. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11242. if (vertexArrayObjectExtension != null) {
  11243. this._caps.vertexArrayObject = true;
  11244. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11245. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11246. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11247. }
  11248. else {
  11249. this._caps.vertexArrayObject = false;
  11250. }
  11251. }
  11252. // Instances count
  11253. if (this._webGLVersion > 1) {
  11254. this._caps.instancedArrays = true;
  11255. }
  11256. else {
  11257. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11258. if (instanceExtension != null) {
  11259. this._caps.instancedArrays = true;
  11260. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11261. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11262. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11263. }
  11264. else {
  11265. this._caps.instancedArrays = false;
  11266. }
  11267. }
  11268. // Intelligently add supported compressed formats in order to check for.
  11269. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11270. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11271. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11272. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11273. if (this._caps.astc)
  11274. this.texturesSupported.push('-astc.ktx');
  11275. if (this._caps.s3tc)
  11276. this.texturesSupported.push('-dxt.ktx');
  11277. if (this._caps.pvrtc)
  11278. this.texturesSupported.push('-pvrtc.ktx');
  11279. if (this._caps.etc2)
  11280. this.texturesSupported.push('-etc2.ktx');
  11281. if (this._caps.etc1)
  11282. this.texturesSupported.push('-etc1.ktx');
  11283. if (this._gl.getShaderPrecisionFormat) {
  11284. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11285. if (highp) {
  11286. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11287. }
  11288. }
  11289. // Depth buffer
  11290. this.setDepthBuffer(true);
  11291. this.setDepthFunctionToLessOrEqual();
  11292. this.setDepthWrite(true);
  11293. // Texture maps
  11294. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11295. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11296. this._nextFreeTextureSlots.push(slot);
  11297. }
  11298. };
  11299. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11300. get: function () {
  11301. return this._webGLVersion;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11307. /**
  11308. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11309. */
  11310. get: function () {
  11311. return this._isStencilEnable;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Engine.prototype._prepareWorkingCanvas = function () {
  11317. if (this._workingCanvas) {
  11318. return;
  11319. }
  11320. this._workingCanvas = document.createElement("canvas");
  11321. var context = this._workingCanvas.getContext("2d");
  11322. if (context) {
  11323. this._workingContext = context;
  11324. }
  11325. };
  11326. Engine.prototype.resetTextureCache = function () {
  11327. for (var key in this._boundTexturesCache) {
  11328. var boundTexture = this._boundTexturesCache[key];
  11329. if (boundTexture) {
  11330. this._removeDesignatedSlot(boundTexture);
  11331. }
  11332. this._boundTexturesCache[key] = null;
  11333. }
  11334. if (!this.disableTextureBindingOptimization) {
  11335. this._nextFreeTextureSlots = [];
  11336. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11337. this._nextFreeTextureSlots.push(slot);
  11338. }
  11339. }
  11340. this._currentTextureChannel = -1;
  11341. };
  11342. Engine.prototype.isDeterministicLockStep = function () {
  11343. return this._deterministicLockstep;
  11344. };
  11345. Engine.prototype.getLockstepMaxSteps = function () {
  11346. return this._lockstepMaxSteps;
  11347. };
  11348. Engine.prototype.getGlInfo = function () {
  11349. return {
  11350. vendor: this._glVendor,
  11351. renderer: this._glRenderer,
  11352. version: this._glVersion
  11353. };
  11354. };
  11355. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11356. if (useScreen === void 0) { useScreen = false; }
  11357. var viewport = camera.viewport;
  11358. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11359. };
  11360. Engine.prototype.getRenderWidth = function (useScreen) {
  11361. if (useScreen === void 0) { useScreen = false; }
  11362. if (!useScreen && this._currentRenderTarget) {
  11363. return this._currentRenderTarget.width;
  11364. }
  11365. return this._gl.drawingBufferWidth;
  11366. };
  11367. Engine.prototype.getRenderHeight = function (useScreen) {
  11368. if (useScreen === void 0) { useScreen = false; }
  11369. if (!useScreen && this._currentRenderTarget) {
  11370. return this._currentRenderTarget.height;
  11371. }
  11372. return this._gl.drawingBufferHeight;
  11373. };
  11374. Engine.prototype.getRenderingCanvas = function () {
  11375. return this._renderingCanvas;
  11376. };
  11377. Engine.prototype.getRenderingCanvasClientRect = function () {
  11378. if (!this._renderingCanvas) {
  11379. return null;
  11380. }
  11381. return this._renderingCanvas.getBoundingClientRect();
  11382. };
  11383. Engine.prototype.setHardwareScalingLevel = function (level) {
  11384. this._hardwareScalingLevel = level;
  11385. this.resize();
  11386. };
  11387. Engine.prototype.getHardwareScalingLevel = function () {
  11388. return this._hardwareScalingLevel;
  11389. };
  11390. Engine.prototype.getLoadedTexturesCache = function () {
  11391. return this._internalTexturesCache;
  11392. };
  11393. Engine.prototype.getCaps = function () {
  11394. return this._caps;
  11395. };
  11396. Object.defineProperty(Engine.prototype, "drawCalls", {
  11397. /** The number of draw calls submitted last frame */
  11398. get: function () {
  11399. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11400. return 0;
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11406. get: function () {
  11407. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11408. return null;
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Engine.prototype.getDepthFunction = function () {
  11414. return this._depthCullingState.depthFunc;
  11415. };
  11416. Engine.prototype.setDepthFunction = function (depthFunc) {
  11417. this._depthCullingState.depthFunc = depthFunc;
  11418. };
  11419. Engine.prototype.setDepthFunctionToGreater = function () {
  11420. this._depthCullingState.depthFunc = this._gl.GREATER;
  11421. };
  11422. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11423. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11424. };
  11425. Engine.prototype.setDepthFunctionToLess = function () {
  11426. this._depthCullingState.depthFunc = this._gl.LESS;
  11427. };
  11428. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11429. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11430. };
  11431. Engine.prototype.getStencilBuffer = function () {
  11432. return this._stencilState.stencilTest;
  11433. };
  11434. Engine.prototype.setStencilBuffer = function (enable) {
  11435. this._stencilState.stencilTest = enable;
  11436. };
  11437. Engine.prototype.getStencilMask = function () {
  11438. return this._stencilState.stencilMask;
  11439. };
  11440. Engine.prototype.setStencilMask = function (mask) {
  11441. this._stencilState.stencilMask = mask;
  11442. };
  11443. Engine.prototype.getStencilFunction = function () {
  11444. return this._stencilState.stencilFunc;
  11445. };
  11446. Engine.prototype.getStencilFunctionReference = function () {
  11447. return this._stencilState.stencilFuncRef;
  11448. };
  11449. Engine.prototype.getStencilFunctionMask = function () {
  11450. return this._stencilState.stencilFuncMask;
  11451. };
  11452. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11453. this._stencilState.stencilFunc = stencilFunc;
  11454. };
  11455. Engine.prototype.setStencilFunctionReference = function (reference) {
  11456. this._stencilState.stencilFuncRef = reference;
  11457. };
  11458. Engine.prototype.setStencilFunctionMask = function (mask) {
  11459. this._stencilState.stencilFuncMask = mask;
  11460. };
  11461. Engine.prototype.getStencilOperationFail = function () {
  11462. return this._stencilState.stencilOpStencilFail;
  11463. };
  11464. Engine.prototype.getStencilOperationDepthFail = function () {
  11465. return this._stencilState.stencilOpDepthFail;
  11466. };
  11467. Engine.prototype.getStencilOperationPass = function () {
  11468. return this._stencilState.stencilOpStencilDepthPass;
  11469. };
  11470. Engine.prototype.setStencilOperationFail = function (operation) {
  11471. this._stencilState.stencilOpStencilFail = operation;
  11472. };
  11473. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11474. this._stencilState.stencilOpDepthFail = operation;
  11475. };
  11476. Engine.prototype.setStencilOperationPass = function (operation) {
  11477. this._stencilState.stencilOpStencilDepthPass = operation;
  11478. };
  11479. Engine.prototype.setDitheringState = function (value) {
  11480. if (value) {
  11481. this._gl.enable(this._gl.DITHER);
  11482. }
  11483. else {
  11484. this._gl.disable(this._gl.DITHER);
  11485. }
  11486. };
  11487. Engine.prototype.setRasterizerState = function (value) {
  11488. if (value) {
  11489. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11490. }
  11491. else {
  11492. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11493. }
  11494. };
  11495. /**
  11496. * stop executing a render loop function and remove it from the execution array
  11497. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11498. */
  11499. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11500. if (!renderFunction) {
  11501. this._activeRenderLoops = [];
  11502. return;
  11503. }
  11504. var index = this._activeRenderLoops.indexOf(renderFunction);
  11505. if (index >= 0) {
  11506. this._activeRenderLoops.splice(index, 1);
  11507. }
  11508. };
  11509. Engine.prototype._renderLoop = function () {
  11510. if (!this._contextWasLost) {
  11511. var shouldRender = true;
  11512. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11513. shouldRender = false;
  11514. }
  11515. if (shouldRender) {
  11516. // Start new frame
  11517. this.beginFrame();
  11518. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11519. var renderFunction = this._activeRenderLoops[index];
  11520. renderFunction();
  11521. }
  11522. // Present
  11523. this.endFrame();
  11524. }
  11525. }
  11526. if (this._activeRenderLoops.length > 0) {
  11527. // Register new frame
  11528. var requester = null;
  11529. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11530. requester = this._vrDisplay;
  11531. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11532. }
  11533. else {
  11534. this._renderingQueueLaunched = false;
  11535. }
  11536. };
  11537. /**
  11538. * Register and execute a render loop. The engine can have more than one render function.
  11539. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11540. * @example
  11541. * engine.runRenderLoop(function () {
  11542. * scene.render()
  11543. * })
  11544. */
  11545. Engine.prototype.runRenderLoop = function (renderFunction) {
  11546. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11547. return;
  11548. }
  11549. this._activeRenderLoops.push(renderFunction);
  11550. if (!this._renderingQueueLaunched) {
  11551. this._renderingQueueLaunched = true;
  11552. this._bindedRenderFunction = this._renderLoop.bind(this);
  11553. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11554. }
  11555. };
  11556. /**
  11557. * Toggle full screen mode.
  11558. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11559. * @param {any} options - an options object to be sent to the requestFullscreen function
  11560. */
  11561. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11562. if (this.isFullscreen) {
  11563. BABYLON.Tools.ExitFullscreen();
  11564. }
  11565. else {
  11566. this._pointerLockRequested = requestPointerLock;
  11567. if (this._renderingCanvas) {
  11568. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11569. }
  11570. }
  11571. };
  11572. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11573. if (stencil === void 0) { stencil = false; }
  11574. this.applyStates();
  11575. var mode = 0;
  11576. if (backBuffer && color) {
  11577. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11578. mode |= this._gl.COLOR_BUFFER_BIT;
  11579. }
  11580. if (depth) {
  11581. this._gl.clearDepth(1.0);
  11582. mode |= this._gl.DEPTH_BUFFER_BIT;
  11583. }
  11584. if (stencil) {
  11585. this._gl.clearStencil(0);
  11586. mode |= this._gl.STENCIL_BUFFER_BIT;
  11587. }
  11588. this._gl.clear(mode);
  11589. };
  11590. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11591. var gl = this._gl;
  11592. // Save state
  11593. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11594. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11595. // Change state
  11596. gl.enable(gl.SCISSOR_TEST);
  11597. gl.scissor(x, y, width, height);
  11598. // Clear
  11599. this.clear(clearColor, true, true, true);
  11600. // Restore state
  11601. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11602. if (curScissor === true) {
  11603. gl.enable(gl.SCISSOR_TEST);
  11604. }
  11605. else {
  11606. gl.disable(gl.SCISSOR_TEST);
  11607. }
  11608. };
  11609. /**
  11610. * Set the WebGL's viewport
  11611. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11612. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11613. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11614. */
  11615. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11616. var width = requiredWidth || this.getRenderWidth();
  11617. var height = requiredHeight || this.getRenderHeight();
  11618. var x = viewport.x || 0;
  11619. var y = viewport.y || 0;
  11620. this._cachedViewport = viewport;
  11621. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11622. };
  11623. /**
  11624. * Directly set the WebGL Viewport
  11625. * The x, y, width & height are directly passed to the WebGL call
  11626. * @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.
  11627. */
  11628. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11629. var currentViewport = this._cachedViewport;
  11630. this._cachedViewport = null;
  11631. this._gl.viewport(x, y, width, height);
  11632. return currentViewport;
  11633. };
  11634. Engine.prototype.beginFrame = function () {
  11635. this.onBeginFrameObservable.notifyObservers(this);
  11636. this._measureFps();
  11637. };
  11638. Engine.prototype.endFrame = function () {
  11639. //force a flush in case we are using a bad OS.
  11640. if (this._badOS) {
  11641. this.flushFramebuffer();
  11642. }
  11643. //submit frame to the vr device, if enabled
  11644. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11645. // TODO: We should only submit the frame if we read frameData successfully.
  11646. this._vrDisplay.submitFrame();
  11647. }
  11648. this.onEndFrameObservable.notifyObservers(this);
  11649. };
  11650. /**
  11651. * resize the view according to the canvas' size.
  11652. * @example
  11653. * window.addEventListener("resize", function () {
  11654. * engine.resize();
  11655. * });
  11656. */
  11657. Engine.prototype.resize = function () {
  11658. // We're not resizing the size of the canvas while in VR mode & presenting
  11659. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11660. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11661. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11662. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11663. }
  11664. };
  11665. /**
  11666. * force a specific size of the canvas
  11667. * @param {number} width - the new canvas' width
  11668. * @param {number} height - the new canvas' height
  11669. */
  11670. Engine.prototype.setSize = function (width, height) {
  11671. if (!this._renderingCanvas) {
  11672. return;
  11673. }
  11674. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11675. return;
  11676. }
  11677. this._renderingCanvas.width = width;
  11678. this._renderingCanvas.height = height;
  11679. for (var index = 0; index < this.scenes.length; index++) {
  11680. var scene = this.scenes[index];
  11681. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11682. var cam = scene.cameras[camIndex];
  11683. cam._currentRenderId = 0;
  11684. }
  11685. }
  11686. if (this.onResizeObservable.hasObservers) {
  11687. this.onResizeObservable.notifyObservers(this);
  11688. }
  11689. };
  11690. // WebVR functions
  11691. Engine.prototype.isVRDevicePresent = function () {
  11692. return !!this._vrDisplay;
  11693. };
  11694. Engine.prototype.getVRDevice = function () {
  11695. return this._vrDisplay;
  11696. };
  11697. /**
  11698. * Initializes a webVR display and starts listening to display change events.
  11699. * The onVRDisplayChangedObservable will be notified upon these changes.
  11700. * @returns The onVRDisplayChangedObservable.
  11701. */
  11702. Engine.prototype.initWebVR = function () {
  11703. this.initWebVRAsync();
  11704. return this.onVRDisplayChangedObservable;
  11705. };
  11706. /**
  11707. * Initializes a webVR display and starts listening to display change events.
  11708. * The onVRDisplayChangedObservable will be notified upon these changes.
  11709. * @returns A promise containing a VRDisplay and if vr is supported.
  11710. */
  11711. Engine.prototype.initWebVRAsync = function () {
  11712. var _this = this;
  11713. var notifyObservers = function () {
  11714. var eventArgs = {
  11715. vrDisplay: _this._vrDisplay,
  11716. vrSupported: _this._vrSupported
  11717. };
  11718. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11719. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11720. };
  11721. if (!this._onVrDisplayConnect) {
  11722. this._onVrDisplayConnect = function (event) {
  11723. _this._vrDisplay = event.display;
  11724. notifyObservers();
  11725. };
  11726. this._onVrDisplayDisconnect = function () {
  11727. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11728. _this._vrDisplay = undefined;
  11729. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11730. notifyObservers();
  11731. };
  11732. this._onVrDisplayPresentChange = function () {
  11733. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11734. };
  11735. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11736. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11737. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11738. }
  11739. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11740. this._webVRInitPromise.then(notifyObservers);
  11741. return this._webVRInitPromise;
  11742. };
  11743. Engine.prototype.enableVR = function () {
  11744. var _this = this;
  11745. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11746. var onResolved = function () {
  11747. _this.onVRRequestPresentComplete.notifyObservers(true);
  11748. _this._onVRFullScreenTriggered();
  11749. };
  11750. var onRejected = function () {
  11751. _this.onVRRequestPresentComplete.notifyObservers(false);
  11752. };
  11753. this.onVRRequestPresentStart.notifyObservers(this);
  11754. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11755. }
  11756. };
  11757. Engine.prototype.disableVR = function () {
  11758. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11759. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11760. }
  11761. };
  11762. Engine.prototype._getVRDisplaysAsync = function () {
  11763. var _this = this;
  11764. return new Promise(function (res, rej) {
  11765. if (navigator.getVRDisplays) {
  11766. navigator.getVRDisplays().then(function (devices) {
  11767. _this._vrSupported = true;
  11768. // note that devices may actually be an empty array. This is fine;
  11769. // we expect this._vrDisplay to be undefined in this case.
  11770. _this._vrDisplay = devices[0];
  11771. res({
  11772. vrDisplay: _this._vrDisplay,
  11773. vrSupported: _this._vrSupported
  11774. });
  11775. });
  11776. }
  11777. else {
  11778. _this._vrDisplay = undefined;
  11779. _this._vrSupported = false;
  11780. res({
  11781. vrDisplay: _this._vrDisplay,
  11782. vrSupported: _this._vrSupported
  11783. });
  11784. }
  11785. });
  11786. };
  11787. /**
  11788. * Binds the frame buffer to the specified texture.
  11789. * @param texture The texture to render to or null for the default canvas
  11790. * @param faceIndex The face of the texture to render to in case of cube texture
  11791. * @param requiredWidth The width of the target to render to
  11792. * @param requiredHeight The height of the target to render to
  11793. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11794. * @param depthStencilTexture The depth stencil texture to use to render
  11795. */
  11796. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11797. if (this._currentRenderTarget) {
  11798. this.unBindFramebuffer(this._currentRenderTarget);
  11799. }
  11800. this._currentRenderTarget = texture;
  11801. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11802. var gl = this._gl;
  11803. if (texture.isCube) {
  11804. if (faceIndex === undefined) {
  11805. faceIndex = 0;
  11806. }
  11807. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11808. if (depthStencilTexture) {
  11809. if (depthStencilTexture._generateStencilBuffer) {
  11810. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11811. }
  11812. else {
  11813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11814. }
  11815. }
  11816. }
  11817. if (this._cachedViewport && !forceFullscreenViewport) {
  11818. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11819. }
  11820. else {
  11821. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11822. }
  11823. this.wipeCaches();
  11824. };
  11825. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11826. if (this._currentFramebuffer !== framebuffer) {
  11827. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11828. this._currentFramebuffer = framebuffer;
  11829. }
  11830. };
  11831. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11832. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11833. this._currentRenderTarget = null;
  11834. // If MSAA, we need to bitblt back to main texture
  11835. var gl = this._gl;
  11836. if (texture._MSAAFramebuffer) {
  11837. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11838. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11839. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11840. }
  11841. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11842. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11843. gl.generateMipmap(gl.TEXTURE_2D);
  11844. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11845. }
  11846. if (onBeforeUnbind) {
  11847. if (texture._MSAAFramebuffer) {
  11848. // Bind the correct framebuffer
  11849. this.bindUnboundFramebuffer(texture._framebuffer);
  11850. }
  11851. onBeforeUnbind();
  11852. }
  11853. this.bindUnboundFramebuffer(null);
  11854. };
  11855. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11856. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11857. this._currentRenderTarget = null;
  11858. // If MSAA, we need to bitblt back to main texture
  11859. var gl = this._gl;
  11860. if (textures[0]._MSAAFramebuffer) {
  11861. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11862. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11863. var attachments = textures[0]._attachments;
  11864. if (!attachments) {
  11865. attachments = new Array(textures.length);
  11866. textures[0]._attachments = attachments;
  11867. }
  11868. for (var i = 0; i < textures.length; i++) {
  11869. var texture = textures[i];
  11870. for (var j = 0; j < attachments.length; j++) {
  11871. attachments[j] = gl.NONE;
  11872. }
  11873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11874. gl.readBuffer(attachments[i]);
  11875. gl.drawBuffers(attachments);
  11876. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11877. }
  11878. for (var i = 0; i < attachments.length; i++) {
  11879. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11880. }
  11881. gl.drawBuffers(attachments);
  11882. }
  11883. for (var i = 0; i < textures.length; i++) {
  11884. var texture = textures[i];
  11885. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11886. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11887. gl.generateMipmap(gl.TEXTURE_2D);
  11888. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11889. }
  11890. }
  11891. if (onBeforeUnbind) {
  11892. if (textures[0]._MSAAFramebuffer) {
  11893. // Bind the correct framebuffer
  11894. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11895. }
  11896. onBeforeUnbind();
  11897. }
  11898. this.bindUnboundFramebuffer(null);
  11899. };
  11900. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11901. if (texture.generateMipMaps) {
  11902. var gl = this._gl;
  11903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11904. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11906. }
  11907. };
  11908. Engine.prototype.flushFramebuffer = function () {
  11909. this._gl.flush();
  11910. };
  11911. Engine.prototype.restoreDefaultFramebuffer = function () {
  11912. if (this._currentRenderTarget) {
  11913. this.unBindFramebuffer(this._currentRenderTarget);
  11914. }
  11915. else {
  11916. this.bindUnboundFramebuffer(null);
  11917. }
  11918. if (this._cachedViewport) {
  11919. this.setViewport(this._cachedViewport);
  11920. }
  11921. this.wipeCaches();
  11922. };
  11923. // UBOs
  11924. Engine.prototype.createUniformBuffer = function (elements) {
  11925. var ubo = this._gl.createBuffer();
  11926. if (!ubo) {
  11927. throw new Error("Unable to create uniform buffer");
  11928. }
  11929. this.bindUniformBuffer(ubo);
  11930. if (elements instanceof Float32Array) {
  11931. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11932. }
  11933. else {
  11934. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11935. }
  11936. this.bindUniformBuffer(null);
  11937. ubo.references = 1;
  11938. return ubo;
  11939. };
  11940. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11941. var ubo = this._gl.createBuffer();
  11942. if (!ubo) {
  11943. throw new Error("Unable to create dynamic uniform buffer");
  11944. }
  11945. this.bindUniformBuffer(ubo);
  11946. if (elements instanceof Float32Array) {
  11947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11948. }
  11949. else {
  11950. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11951. }
  11952. this.bindUniformBuffer(null);
  11953. ubo.references = 1;
  11954. return ubo;
  11955. };
  11956. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11957. this.bindUniformBuffer(uniformBuffer);
  11958. if (offset === undefined) {
  11959. offset = 0;
  11960. }
  11961. if (count === undefined) {
  11962. if (elements instanceof Float32Array) {
  11963. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11964. }
  11965. else {
  11966. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11967. }
  11968. }
  11969. else {
  11970. if (elements instanceof Float32Array) {
  11971. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11972. }
  11973. else {
  11974. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11975. }
  11976. }
  11977. this.bindUniformBuffer(null);
  11978. };
  11979. // VBOs
  11980. Engine.prototype._resetVertexBufferBinding = function () {
  11981. this.bindArrayBuffer(null);
  11982. this._cachedVertexBuffers = null;
  11983. };
  11984. Engine.prototype.createVertexBuffer = function (vertices) {
  11985. var vbo = this._gl.createBuffer();
  11986. if (!vbo) {
  11987. throw new Error("Unable to create vertex buffer");
  11988. }
  11989. this.bindArrayBuffer(vbo);
  11990. if (vertices instanceof Float32Array) {
  11991. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11992. }
  11993. else {
  11994. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11995. }
  11996. this._resetVertexBufferBinding();
  11997. vbo.references = 1;
  11998. return vbo;
  11999. };
  12000. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12001. var vbo = this._gl.createBuffer();
  12002. if (!vbo) {
  12003. throw new Error("Unable to create dynamic vertex buffer");
  12004. }
  12005. this.bindArrayBuffer(vbo);
  12006. if (vertices instanceof Float32Array) {
  12007. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12008. }
  12009. else {
  12010. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12011. }
  12012. this._resetVertexBufferBinding();
  12013. vbo.references = 1;
  12014. return vbo;
  12015. };
  12016. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12017. if (offset === void 0) { offset = 0; }
  12018. // Force cache update
  12019. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12020. this.bindIndexBuffer(indexBuffer);
  12021. var arrayBuffer;
  12022. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12023. arrayBuffer = indices;
  12024. }
  12025. else {
  12026. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12027. }
  12028. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12029. this._resetIndexBufferBinding();
  12030. };
  12031. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12032. this.bindArrayBuffer(vertexBuffer);
  12033. if (offset === undefined) {
  12034. offset = 0;
  12035. }
  12036. if (count === undefined) {
  12037. if (vertices instanceof Float32Array) {
  12038. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12039. }
  12040. else {
  12041. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12042. }
  12043. }
  12044. else {
  12045. if (vertices instanceof Float32Array) {
  12046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12047. }
  12048. else {
  12049. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12050. }
  12051. }
  12052. this._resetVertexBufferBinding();
  12053. };
  12054. Engine.prototype._resetIndexBufferBinding = function () {
  12055. this.bindIndexBuffer(null);
  12056. this._cachedIndexBuffer = null;
  12057. };
  12058. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12059. var vbo = this._gl.createBuffer();
  12060. if (!vbo) {
  12061. throw new Error("Unable to create index buffer");
  12062. }
  12063. this.bindIndexBuffer(vbo);
  12064. // Check for 32 bits indices
  12065. var arrayBuffer;
  12066. var need32Bits = false;
  12067. if (indices instanceof Uint16Array) {
  12068. arrayBuffer = indices;
  12069. }
  12070. else {
  12071. //check 32 bit support
  12072. if (this._caps.uintIndices) {
  12073. if (indices instanceof Uint32Array) {
  12074. arrayBuffer = indices;
  12075. need32Bits = true;
  12076. }
  12077. else {
  12078. //number[] or Int32Array, check if 32 bit is necessary
  12079. for (var index = 0; index < indices.length; index++) {
  12080. if (indices[index] > 65535) {
  12081. need32Bits = true;
  12082. break;
  12083. }
  12084. }
  12085. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12086. }
  12087. }
  12088. else {
  12089. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12090. arrayBuffer = new Uint16Array(indices);
  12091. }
  12092. }
  12093. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12094. this._resetIndexBufferBinding();
  12095. vbo.references = 1;
  12096. vbo.is32Bits = need32Bits;
  12097. return vbo;
  12098. };
  12099. Engine.prototype.bindArrayBuffer = function (buffer) {
  12100. if (!this._vaoRecordInProgress) {
  12101. this._unbindVertexArrayObject();
  12102. }
  12103. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12104. };
  12105. Engine.prototype.bindUniformBuffer = function (buffer) {
  12106. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12107. };
  12108. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12109. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12110. };
  12111. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12112. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12113. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12114. };
  12115. ;
  12116. Engine.prototype.bindIndexBuffer = function (buffer) {
  12117. if (!this._vaoRecordInProgress) {
  12118. this._unbindVertexArrayObject();
  12119. }
  12120. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12121. };
  12122. Engine.prototype.bindBuffer = function (buffer, target) {
  12123. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12124. this._gl.bindBuffer(target, buffer);
  12125. this._currentBoundBuffer[target] = buffer;
  12126. }
  12127. };
  12128. Engine.prototype.updateArrayBuffer = function (data) {
  12129. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12130. };
  12131. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12132. var pointer = this._currentBufferPointers[indx];
  12133. var changed = false;
  12134. if (!pointer.active) {
  12135. changed = true;
  12136. pointer.active = true;
  12137. pointer.index = indx;
  12138. pointer.size = size;
  12139. pointer.type = type;
  12140. pointer.normalized = normalized;
  12141. pointer.stride = stride;
  12142. pointer.offset = offset;
  12143. pointer.buffer = buffer;
  12144. }
  12145. else {
  12146. if (pointer.buffer !== buffer) {
  12147. pointer.buffer = buffer;
  12148. changed = true;
  12149. }
  12150. if (pointer.size !== size) {
  12151. pointer.size = size;
  12152. changed = true;
  12153. }
  12154. if (pointer.type !== type) {
  12155. pointer.type = type;
  12156. changed = true;
  12157. }
  12158. if (pointer.normalized !== normalized) {
  12159. pointer.normalized = normalized;
  12160. changed = true;
  12161. }
  12162. if (pointer.stride !== stride) {
  12163. pointer.stride = stride;
  12164. changed = true;
  12165. }
  12166. if (pointer.offset !== offset) {
  12167. pointer.offset = offset;
  12168. changed = true;
  12169. }
  12170. }
  12171. if (changed || this._vaoRecordInProgress) {
  12172. this.bindArrayBuffer(buffer);
  12173. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12174. }
  12175. };
  12176. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12177. if (indexBuffer == null) {
  12178. return;
  12179. }
  12180. if (this._cachedIndexBuffer !== indexBuffer) {
  12181. this._cachedIndexBuffer = indexBuffer;
  12182. this.bindIndexBuffer(indexBuffer);
  12183. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12184. }
  12185. };
  12186. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12187. var attributes = effect.getAttributesNames();
  12188. if (!this._vaoRecordInProgress) {
  12189. this._unbindVertexArrayObject();
  12190. }
  12191. this.unbindAllAttributes();
  12192. for (var index = 0; index < attributes.length; index++) {
  12193. var order = effect.getAttributeLocation(index);
  12194. if (order >= 0) {
  12195. var vertexBuffer = vertexBuffers[attributes[index]];
  12196. if (!vertexBuffer) {
  12197. continue;
  12198. }
  12199. this._gl.enableVertexAttribArray(order);
  12200. if (!this._vaoRecordInProgress) {
  12201. this._vertexAttribArraysEnabled[order] = true;
  12202. }
  12203. var buffer = vertexBuffer.getBuffer();
  12204. if (buffer) {
  12205. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12206. if (vertexBuffer.getIsInstanced()) {
  12207. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12208. if (!this._vaoRecordInProgress) {
  12209. this._currentInstanceLocations.push(order);
  12210. this._currentInstanceBuffers.push(buffer);
  12211. }
  12212. }
  12213. }
  12214. }
  12215. }
  12216. };
  12217. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12218. var vao = this._gl.createVertexArray();
  12219. this._vaoRecordInProgress = true;
  12220. this._gl.bindVertexArray(vao);
  12221. this._mustWipeVertexAttributes = true;
  12222. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12223. this.bindIndexBuffer(indexBuffer);
  12224. this._vaoRecordInProgress = false;
  12225. this._gl.bindVertexArray(null);
  12226. return vao;
  12227. };
  12228. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12229. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12230. this._cachedVertexArrayObject = vertexArrayObject;
  12231. this._gl.bindVertexArray(vertexArrayObject);
  12232. this._cachedVertexBuffers = null;
  12233. this._cachedIndexBuffer = null;
  12234. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12235. this._mustWipeVertexAttributes = true;
  12236. }
  12237. };
  12238. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12239. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12240. this._cachedVertexBuffers = vertexBuffer;
  12241. this._cachedEffectForVertexBuffers = effect;
  12242. var attributesCount = effect.getAttributesCount();
  12243. this._unbindVertexArrayObject();
  12244. this.unbindAllAttributes();
  12245. var offset = 0;
  12246. for (var index = 0; index < attributesCount; index++) {
  12247. if (index < vertexDeclaration.length) {
  12248. var order = effect.getAttributeLocation(index);
  12249. if (order >= 0) {
  12250. this._gl.enableVertexAttribArray(order);
  12251. this._vertexAttribArraysEnabled[order] = true;
  12252. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12253. }
  12254. offset += vertexDeclaration[index] * 4;
  12255. }
  12256. }
  12257. }
  12258. this._bindIndexBufferWithCache(indexBuffer);
  12259. };
  12260. Engine.prototype._unbindVertexArrayObject = function () {
  12261. if (!this._cachedVertexArrayObject) {
  12262. return;
  12263. }
  12264. this._cachedVertexArrayObject = null;
  12265. this._gl.bindVertexArray(null);
  12266. };
  12267. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12268. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12269. this._cachedVertexBuffers = vertexBuffers;
  12270. this._cachedEffectForVertexBuffers = effect;
  12271. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12272. }
  12273. this._bindIndexBufferWithCache(indexBuffer);
  12274. };
  12275. Engine.prototype.unbindInstanceAttributes = function () {
  12276. var boundBuffer;
  12277. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12278. var instancesBuffer = this._currentInstanceBuffers[i];
  12279. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12280. boundBuffer = instancesBuffer;
  12281. this.bindArrayBuffer(instancesBuffer);
  12282. }
  12283. var offsetLocation = this._currentInstanceLocations[i];
  12284. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12285. }
  12286. this._currentInstanceBuffers.length = 0;
  12287. this._currentInstanceLocations.length = 0;
  12288. };
  12289. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12290. this._gl.deleteVertexArray(vao);
  12291. };
  12292. Engine.prototype._releaseBuffer = function (buffer) {
  12293. buffer.references--;
  12294. if (buffer.references === 0) {
  12295. this._gl.deleteBuffer(buffer);
  12296. return true;
  12297. }
  12298. return false;
  12299. };
  12300. Engine.prototype.createInstancesBuffer = function (capacity) {
  12301. var buffer = this._gl.createBuffer();
  12302. if (!buffer) {
  12303. throw new Error("Unable to create instance buffer");
  12304. }
  12305. buffer.capacity = capacity;
  12306. this.bindArrayBuffer(buffer);
  12307. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12308. return buffer;
  12309. };
  12310. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12311. this._gl.deleteBuffer(buffer);
  12312. };
  12313. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12314. this.bindArrayBuffer(instancesBuffer);
  12315. if (data) {
  12316. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12317. }
  12318. if (offsetLocations[0].index !== undefined) {
  12319. var stride = 0;
  12320. for (var i = 0; i < offsetLocations.length; i++) {
  12321. var ai = offsetLocations[i];
  12322. stride += ai.attributeSize * 4;
  12323. }
  12324. for (var i = 0; i < offsetLocations.length; i++) {
  12325. var ai = offsetLocations[i];
  12326. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12327. this._gl.enableVertexAttribArray(ai.index);
  12328. this._vertexAttribArraysEnabled[ai.index] = true;
  12329. }
  12330. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12331. this._gl.vertexAttribDivisor(ai.index, 1);
  12332. this._currentInstanceLocations.push(ai.index);
  12333. this._currentInstanceBuffers.push(instancesBuffer);
  12334. }
  12335. }
  12336. else {
  12337. for (var index = 0; index < 4; index++) {
  12338. var offsetLocation = offsetLocations[index];
  12339. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12340. this._gl.enableVertexAttribArray(offsetLocation);
  12341. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12342. }
  12343. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12344. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12345. this._currentInstanceLocations.push(offsetLocation);
  12346. this._currentInstanceBuffers.push(instancesBuffer);
  12347. }
  12348. }
  12349. };
  12350. Engine.prototype.applyStates = function () {
  12351. this._depthCullingState.apply(this._gl);
  12352. this._stencilState.apply(this._gl);
  12353. this._alphaState.apply(this._gl);
  12354. };
  12355. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12356. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12357. };
  12358. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12359. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12360. };
  12361. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12362. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12363. };
  12364. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12365. // Apply states
  12366. this.applyStates();
  12367. this._drawCalls.addCount(1, false);
  12368. // Render
  12369. var drawMode = this.DrawMode(fillMode);
  12370. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12371. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12372. if (instancesCount) {
  12373. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12374. }
  12375. else {
  12376. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12377. }
  12378. };
  12379. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12380. // Apply states
  12381. this.applyStates();
  12382. this._drawCalls.addCount(1, false);
  12383. var drawMode = this.DrawMode(fillMode);
  12384. if (instancesCount) {
  12385. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12386. }
  12387. else {
  12388. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12389. }
  12390. };
  12391. Engine.prototype.DrawMode = function (fillMode) {
  12392. switch (fillMode) {
  12393. // Triangle views
  12394. case BABYLON.Material.TriangleFillMode:
  12395. return this._gl.TRIANGLES;
  12396. case BABYLON.Material.PointFillMode:
  12397. return this._gl.POINTS;
  12398. case BABYLON.Material.WireFrameFillMode:
  12399. return this._gl.LINES;
  12400. // Draw modes
  12401. case BABYLON.Material.PointListDrawMode:
  12402. return this._gl.POINTS;
  12403. case BABYLON.Material.LineListDrawMode:
  12404. return this._gl.LINES;
  12405. case BABYLON.Material.LineLoopDrawMode:
  12406. return this._gl.LINE_LOOP;
  12407. case BABYLON.Material.LineStripDrawMode:
  12408. return this._gl.LINE_STRIP;
  12409. case BABYLON.Material.TriangleStripDrawMode:
  12410. return this._gl.TRIANGLE_STRIP;
  12411. case BABYLON.Material.TriangleFanDrawMode:
  12412. return this._gl.TRIANGLE_FAN;
  12413. default:
  12414. return this._gl.TRIANGLES;
  12415. }
  12416. };
  12417. // Shaders
  12418. Engine.prototype._releaseEffect = function (effect) {
  12419. if (this._compiledEffects[effect._key]) {
  12420. delete this._compiledEffects[effect._key];
  12421. this._deleteProgram(effect.getProgram());
  12422. }
  12423. };
  12424. Engine.prototype._deleteProgram = function (program) {
  12425. if (program) {
  12426. program.__SPECTOR_rebuildProgram = null;
  12427. if (program.transformFeedback) {
  12428. this.deleteTransformFeedback(program.transformFeedback);
  12429. program.transformFeedback = null;
  12430. }
  12431. this._gl.deleteProgram(program);
  12432. }
  12433. };
  12434. /**
  12435. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12436. * @param samplers An array of string used to represent textures
  12437. */
  12438. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12439. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12440. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12441. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12442. if (this._compiledEffects[name]) {
  12443. var compiledEffect = this._compiledEffects[name];
  12444. if (onCompiled && compiledEffect.isReady()) {
  12445. onCompiled(compiledEffect);
  12446. }
  12447. return compiledEffect;
  12448. }
  12449. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12450. effect._key = name;
  12451. this._compiledEffects[name] = effect;
  12452. return effect;
  12453. };
  12454. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12455. if (uniformsNames === void 0) { uniformsNames = []; }
  12456. if (samplers === void 0) { samplers = []; }
  12457. if (defines === void 0) { defines = ""; }
  12458. return this.createEffect({
  12459. vertex: "particles",
  12460. fragmentElement: fragmentName
  12461. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12462. };
  12463. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12464. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12465. context = context || this._gl;
  12466. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12467. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12468. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12469. };
  12470. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12471. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12472. context = context || this._gl;
  12473. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12474. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12475. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12476. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12477. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12478. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12479. return program;
  12480. };
  12481. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12482. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12483. var shaderProgram = context.createProgram();
  12484. if (!shaderProgram) {
  12485. throw new Error("Unable to create program");
  12486. }
  12487. context.attachShader(shaderProgram, vertexShader);
  12488. context.attachShader(shaderProgram, fragmentShader);
  12489. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12490. var transformFeedback = this.createTransformFeedback();
  12491. this.bindTransformFeedback(transformFeedback);
  12492. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12493. shaderProgram.transformFeedback = transformFeedback;
  12494. }
  12495. context.linkProgram(shaderProgram);
  12496. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12497. this.bindTransformFeedback(null);
  12498. }
  12499. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12500. if (!linked) {
  12501. context.validateProgram(shaderProgram);
  12502. var error = context.getProgramInfoLog(shaderProgram);
  12503. if (error) {
  12504. throw new Error(error);
  12505. }
  12506. }
  12507. context.deleteShader(vertexShader);
  12508. context.deleteShader(fragmentShader);
  12509. return shaderProgram;
  12510. };
  12511. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12512. var results = new Array();
  12513. for (var index = 0; index < uniformsNames.length; index++) {
  12514. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12515. }
  12516. return results;
  12517. };
  12518. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12519. var results = [];
  12520. for (var index = 0; index < attributesNames.length; index++) {
  12521. try {
  12522. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12523. }
  12524. catch (e) {
  12525. results.push(-1);
  12526. }
  12527. }
  12528. return results;
  12529. };
  12530. Engine.prototype.enableEffect = function (effect) {
  12531. if (!effect) {
  12532. return;
  12533. }
  12534. // Use program
  12535. this.bindSamplers(effect);
  12536. this._currentEffect = effect;
  12537. if (effect.onBind) {
  12538. effect.onBind(effect);
  12539. }
  12540. effect.onBindObservable.notifyObservers(effect);
  12541. };
  12542. Engine.prototype.setIntArray = function (uniform, array) {
  12543. if (!uniform)
  12544. return;
  12545. this._gl.uniform1iv(uniform, array);
  12546. };
  12547. Engine.prototype.setIntArray2 = function (uniform, array) {
  12548. if (!uniform || array.length % 2 !== 0)
  12549. return;
  12550. this._gl.uniform2iv(uniform, array);
  12551. };
  12552. Engine.prototype.setIntArray3 = function (uniform, array) {
  12553. if (!uniform || array.length % 3 !== 0)
  12554. return;
  12555. this._gl.uniform3iv(uniform, array);
  12556. };
  12557. Engine.prototype.setIntArray4 = function (uniform, array) {
  12558. if (!uniform || array.length % 4 !== 0)
  12559. return;
  12560. this._gl.uniform4iv(uniform, array);
  12561. };
  12562. Engine.prototype.setFloatArray = function (uniform, array) {
  12563. if (!uniform)
  12564. return;
  12565. this._gl.uniform1fv(uniform, array);
  12566. };
  12567. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12568. if (!uniform || array.length % 2 !== 0)
  12569. return;
  12570. this._gl.uniform2fv(uniform, array);
  12571. };
  12572. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12573. if (!uniform || array.length % 3 !== 0)
  12574. return;
  12575. this._gl.uniform3fv(uniform, array);
  12576. };
  12577. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12578. if (!uniform || array.length % 4 !== 0)
  12579. return;
  12580. this._gl.uniform4fv(uniform, array);
  12581. };
  12582. Engine.prototype.setArray = function (uniform, array) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniform1fv(uniform, array);
  12586. };
  12587. Engine.prototype.setArray2 = function (uniform, array) {
  12588. if (!uniform || array.length % 2 !== 0)
  12589. return;
  12590. this._gl.uniform2fv(uniform, array);
  12591. };
  12592. Engine.prototype.setArray3 = function (uniform, array) {
  12593. if (!uniform || array.length % 3 !== 0)
  12594. return;
  12595. this._gl.uniform3fv(uniform, array);
  12596. };
  12597. Engine.prototype.setArray4 = function (uniform, array) {
  12598. if (!uniform || array.length % 4 !== 0)
  12599. return;
  12600. this._gl.uniform4fv(uniform, array);
  12601. };
  12602. Engine.prototype.setMatrices = function (uniform, matrices) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12606. };
  12607. Engine.prototype.setMatrix = function (uniform, matrix) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12611. };
  12612. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12616. };
  12617. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12621. };
  12622. Engine.prototype.setInt = function (uniform, value) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform1i(uniform, value);
  12626. };
  12627. Engine.prototype.setFloat = function (uniform, value) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform1f(uniform, value);
  12631. };
  12632. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12633. if (!uniform)
  12634. return;
  12635. this._gl.uniform2f(uniform, x, y);
  12636. };
  12637. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12638. if (!uniform)
  12639. return;
  12640. this._gl.uniform3f(uniform, x, y, z);
  12641. };
  12642. Engine.prototype.setBool = function (uniform, bool) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniform1i(uniform, bool);
  12646. };
  12647. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12648. if (!uniform)
  12649. return;
  12650. this._gl.uniform4f(uniform, x, y, z, w);
  12651. };
  12652. Engine.prototype.setColor3 = function (uniform, color3) {
  12653. if (!uniform)
  12654. return;
  12655. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12656. };
  12657. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12658. if (!uniform)
  12659. return;
  12660. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12661. };
  12662. /**
  12663. * Sets a Color4 on a uniform variable
  12664. * @param uniform defines the uniform location
  12665. * @param color4 defines the value to be set
  12666. */
  12667. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12668. if (!uniform)
  12669. return;
  12670. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12671. };
  12672. // States
  12673. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12674. if (zOffset === void 0) { zOffset = 0; }
  12675. if (reverseSide === void 0) { reverseSide = false; }
  12676. // Culling
  12677. if (this._depthCullingState.cull !== culling || force) {
  12678. this._depthCullingState.cull = culling;
  12679. }
  12680. // Cull face
  12681. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12682. if (this._depthCullingState.cullFace !== cullFace || force) {
  12683. this._depthCullingState.cullFace = cullFace;
  12684. }
  12685. // Z offset
  12686. this.setZOffset(zOffset);
  12687. // Front face
  12688. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12689. if (this._depthCullingState.frontFace !== frontFace || force) {
  12690. this._depthCullingState.frontFace = frontFace;
  12691. }
  12692. };
  12693. Engine.prototype.setZOffset = function (value) {
  12694. this._depthCullingState.zOffset = value;
  12695. };
  12696. Engine.prototype.getZOffset = function () {
  12697. return this._depthCullingState.zOffset;
  12698. };
  12699. Engine.prototype.setDepthBuffer = function (enable) {
  12700. this._depthCullingState.depthTest = enable;
  12701. };
  12702. Engine.prototype.getDepthWrite = function () {
  12703. return this._depthCullingState.depthMask;
  12704. };
  12705. Engine.prototype.setDepthWrite = function (enable) {
  12706. this._depthCullingState.depthMask = enable;
  12707. };
  12708. Engine.prototype.setColorWrite = function (enable) {
  12709. this._gl.colorMask(enable, enable, enable, enable);
  12710. this._colorWrite = enable;
  12711. };
  12712. Engine.prototype.getColorWrite = function () {
  12713. return this._colorWrite;
  12714. };
  12715. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12716. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12717. };
  12718. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12719. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12720. if (this._alphaMode === mode) {
  12721. return;
  12722. }
  12723. switch (mode) {
  12724. case Engine.ALPHA_DISABLE:
  12725. this._alphaState.alphaBlend = false;
  12726. break;
  12727. case Engine.ALPHA_PREMULTIPLIED:
  12728. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12729. this._alphaState.alphaBlend = true;
  12730. break;
  12731. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12732. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12733. this._alphaState.alphaBlend = true;
  12734. break;
  12735. case Engine.ALPHA_COMBINE:
  12736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12737. this._alphaState.alphaBlend = true;
  12738. break;
  12739. case Engine.ALPHA_ONEONE:
  12740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12741. this._alphaState.alphaBlend = true;
  12742. break;
  12743. case Engine.ALPHA_ADD:
  12744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12745. this._alphaState.alphaBlend = true;
  12746. break;
  12747. case Engine.ALPHA_SUBTRACT:
  12748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12749. this._alphaState.alphaBlend = true;
  12750. break;
  12751. case Engine.ALPHA_MULTIPLY:
  12752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12753. this._alphaState.alphaBlend = true;
  12754. break;
  12755. case Engine.ALPHA_MAXIMIZED:
  12756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12757. this._alphaState.alphaBlend = true;
  12758. break;
  12759. case Engine.ALPHA_INTERPOLATE:
  12760. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12761. this._alphaState.alphaBlend = true;
  12762. break;
  12763. case Engine.ALPHA_SCREENMODE:
  12764. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12765. this._alphaState.alphaBlend = true;
  12766. break;
  12767. }
  12768. if (!noDepthWriteChange) {
  12769. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12770. }
  12771. this._alphaMode = mode;
  12772. };
  12773. Engine.prototype.getAlphaMode = function () {
  12774. return this._alphaMode;
  12775. };
  12776. // Textures
  12777. Engine.prototype.wipeCaches = function (bruteForce) {
  12778. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12779. return;
  12780. }
  12781. this._currentEffect = null;
  12782. // 6/8/2017: deltakosh: Should not be required anymore.
  12783. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12784. if (bruteForce) {
  12785. this.resetTextureCache();
  12786. this._currentProgram = null;
  12787. this._stencilState.reset();
  12788. this._depthCullingState.reset();
  12789. this.setDepthFunctionToLessOrEqual();
  12790. this._alphaState.reset();
  12791. }
  12792. this._resetVertexBufferBinding();
  12793. this._cachedIndexBuffer = null;
  12794. this._cachedEffectForVertexBuffers = null;
  12795. this._unbindVertexArrayObject();
  12796. this.bindIndexBuffer(null);
  12797. };
  12798. /**
  12799. * Set the compressed texture format to use, based on the formats you have, and the formats
  12800. * supported by the hardware / browser.
  12801. *
  12802. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12803. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12804. * to API arguments needed to compressed textures. This puts the burden on the container
  12805. * generator to house the arcane code for determining these for current & future formats.
  12806. *
  12807. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12808. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12809. *
  12810. * Note: The result of this call is not taken into account when a texture is base64.
  12811. *
  12812. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12813. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12814. *
  12815. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12816. * @returns The extension selected.
  12817. */
  12818. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12819. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12820. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12821. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12822. return this._textureFormatInUse = this._texturesSupported[i];
  12823. }
  12824. }
  12825. }
  12826. // actively set format to nothing, to allow this to be called more than once
  12827. // and possibly fail the 2nd time
  12828. this._textureFormatInUse = null;
  12829. return null;
  12830. };
  12831. Engine.prototype._createTexture = function () {
  12832. var texture = this._gl.createTexture();
  12833. if (!texture) {
  12834. throw new Error("Unable to create texture");
  12835. }
  12836. return texture;
  12837. };
  12838. /**
  12839. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12840. * @param {string} urlArg- This contains one of the following:
  12841. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12842. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12843. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12844. *
  12845. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12846. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12847. * @param {Scene} scene- Needed for loading to the correct scene.
  12848. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12849. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12850. * @param {callback} onError- Optional callback to be called upon failure.
  12851. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12852. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12853. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12854. *
  12855. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12856. */
  12857. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12858. var _this = this;
  12859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12860. if (onLoad === void 0) { onLoad = null; }
  12861. if (onError === void 0) { onError = null; }
  12862. if (buffer === void 0) { buffer = null; }
  12863. if (fallBack === void 0) { fallBack = null; }
  12864. if (format === void 0) { format = null; }
  12865. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12866. var fromData = url.substr(0, 5) === "data:";
  12867. var fromBlob = url.substr(0, 5) === "blob:";
  12868. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12869. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12870. // establish the file extension, if possible
  12871. var lastDot = url.lastIndexOf('.');
  12872. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12873. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12874. var isTGA = (extension.indexOf(".tga") === 0);
  12875. // determine if a ktx file should be substituted
  12876. var isKTX = false;
  12877. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12878. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12879. isKTX = true;
  12880. }
  12881. if (scene) {
  12882. scene._addPendingData(texture);
  12883. }
  12884. texture.url = url;
  12885. texture.generateMipMaps = !noMipmap;
  12886. texture.samplingMode = samplingMode;
  12887. texture.invertY = invertY;
  12888. if (!this._doNotHandleContextLost) {
  12889. // Keep a link to the buffer only if we plan to handle context lost
  12890. texture._buffer = buffer;
  12891. }
  12892. var onLoadObserver = null;
  12893. if (onLoad && !fallBack) {
  12894. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12895. }
  12896. if (!fallBack)
  12897. this._internalTexturesCache.push(texture);
  12898. var onerror = function (message, exception) {
  12899. if (scene) {
  12900. scene._removePendingData(texture);
  12901. }
  12902. if (onLoadObserver) {
  12903. texture.onLoadedObservable.remove(onLoadObserver);
  12904. }
  12905. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12906. if (isKTX) {
  12907. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12908. }
  12909. else if (BABYLON.Tools.UseFallbackTexture) {
  12910. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12911. }
  12912. if (onError) {
  12913. onError(message || "Unknown error", exception);
  12914. }
  12915. };
  12916. var callback = null;
  12917. // processing for non-image formats
  12918. if (isKTX || isTGA || isDDS) {
  12919. if (isKTX) {
  12920. callback = function (data) {
  12921. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12922. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12923. ktx.uploadLevels(_this._gl, !noMipmap);
  12924. return false;
  12925. }, samplingMode);
  12926. };
  12927. }
  12928. else if (isTGA) {
  12929. callback = function (arrayBuffer) {
  12930. var data = new Uint8Array(arrayBuffer);
  12931. var header = BABYLON.TGATools.GetTGAHeader(data);
  12932. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12933. BABYLON.TGATools.UploadContent(_this._gl, data);
  12934. return false;
  12935. }, samplingMode);
  12936. };
  12937. }
  12938. else if (isDDS) {
  12939. callback = function (data) {
  12940. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12942. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12943. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12944. return false;
  12945. }, samplingMode);
  12946. };
  12947. }
  12948. if (!buffer) {
  12949. this._loadFile(url, function (data) {
  12950. if (callback) {
  12951. callback(data);
  12952. }
  12953. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12954. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12955. });
  12956. }
  12957. else {
  12958. if (callback) {
  12959. callback(buffer);
  12960. }
  12961. }
  12962. // image format processing
  12963. }
  12964. else {
  12965. var onload = function (img) {
  12966. if (fromBlob && !_this._doNotHandleContextLost) {
  12967. // We need to store the image if we need to rebuild the texture
  12968. // in case of a webgl context lost
  12969. texture._buffer = img;
  12970. }
  12971. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12972. var gl = _this._gl;
  12973. var isPot = (img.width === potWidth && img.height === potHeight);
  12974. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12975. if (isPot) {
  12976. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12977. return false;
  12978. }
  12979. // Using shaders to rescale because canvas.drawImage is lossy
  12980. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12981. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12982. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12987. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12988. _this._releaseTexture(source);
  12989. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12990. continuationCallback();
  12991. });
  12992. return true;
  12993. }, samplingMode);
  12994. };
  12995. if (!fromData || isBase64)
  12996. if (buffer instanceof HTMLImageElement) {
  12997. onload(buffer);
  12998. }
  12999. else {
  13000. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13001. }
  13002. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13003. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13004. else
  13005. onload(buffer);
  13006. }
  13007. return texture;
  13008. };
  13009. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13010. var _this = this;
  13011. var rtt = this.createRenderTargetTexture({
  13012. width: destination.width,
  13013. height: destination.height,
  13014. }, {
  13015. generateMipMaps: false,
  13016. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13017. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13018. generateDepthBuffer: false,
  13019. generateStencilBuffer: false
  13020. });
  13021. if (!this._rescalePostProcess) {
  13022. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13023. }
  13024. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13025. _this._rescalePostProcess.onApply = function (effect) {
  13026. effect._bindTexture("textureSampler", source);
  13027. };
  13028. var hostingScene = scene;
  13029. if (!hostingScene) {
  13030. hostingScene = _this.scenes[_this.scenes.length - 1];
  13031. }
  13032. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13033. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13034. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13035. _this.unBindFramebuffer(rtt);
  13036. _this._releaseTexture(rtt);
  13037. if (onComplete) {
  13038. onComplete();
  13039. }
  13040. });
  13041. };
  13042. Engine.prototype._getInternalFormat = function (format) {
  13043. var internalFormat = this._gl.RGBA;
  13044. switch (format) {
  13045. case Engine.TEXTUREFORMAT_ALPHA:
  13046. internalFormat = this._gl.ALPHA;
  13047. break;
  13048. case Engine.TEXTUREFORMAT_LUMINANCE:
  13049. internalFormat = this._gl.LUMINANCE;
  13050. break;
  13051. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13052. internalFormat = this._gl.LUMINANCE_ALPHA;
  13053. break;
  13054. case Engine.TEXTUREFORMAT_RGB:
  13055. case Engine.TEXTUREFORMAT_RGB32F:
  13056. internalFormat = this._gl.RGB;
  13057. break;
  13058. case Engine.TEXTUREFORMAT_RGBA:
  13059. case Engine.TEXTUREFORMAT_RGBA32F:
  13060. internalFormat = this._gl.RGBA;
  13061. break;
  13062. case Engine.TEXTUREFORMAT_R32F:
  13063. internalFormat = this._gl.RED;
  13064. break;
  13065. case Engine.TEXTUREFORMAT_RG32F:
  13066. internalFormat = this._gl.RG;
  13067. break;
  13068. }
  13069. return internalFormat;
  13070. };
  13071. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13072. if (compression === void 0) { compression = null; }
  13073. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13074. if (!texture) {
  13075. return;
  13076. }
  13077. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13078. var internalFormat = this._getInternalFormat(format);
  13079. var textureType = this._getWebGLTextureType(type);
  13080. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13081. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13082. if (!this._doNotHandleContextLost) {
  13083. texture._bufferView = data;
  13084. texture.format = format;
  13085. texture.type = type;
  13086. texture.invertY = invertY;
  13087. texture._compression = compression;
  13088. }
  13089. if (texture.width % 4 !== 0) {
  13090. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13091. }
  13092. if (compression && data) {
  13093. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13094. }
  13095. else {
  13096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13097. }
  13098. if (texture.generateMipMaps) {
  13099. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13100. }
  13101. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13102. // this.resetTextureCache();
  13103. texture.isReady = true;
  13104. };
  13105. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13106. if (compression === void 0) { compression = null; }
  13107. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13108. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13109. texture.baseWidth = width;
  13110. texture.baseHeight = height;
  13111. texture.width = width;
  13112. texture.height = height;
  13113. texture.format = format;
  13114. texture.generateMipMaps = generateMipMaps;
  13115. texture.samplingMode = samplingMode;
  13116. texture.invertY = invertY;
  13117. texture._compression = compression;
  13118. texture.type = type;
  13119. if (!this._doNotHandleContextLost) {
  13120. texture._bufferView = data;
  13121. }
  13122. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13123. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13124. // Filters
  13125. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13128. if (generateMipMaps) {
  13129. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13130. }
  13131. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13132. this._internalTexturesCache.push(texture);
  13133. return texture;
  13134. };
  13135. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13136. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13137. texture.baseWidth = width;
  13138. texture.baseHeight = height;
  13139. if (generateMipMaps) {
  13140. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13141. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13142. }
  13143. // this.resetTextureCache();
  13144. texture.width = width;
  13145. texture.height = height;
  13146. texture.isReady = false;
  13147. texture.generateMipMaps = generateMipMaps;
  13148. texture.samplingMode = samplingMode;
  13149. this.updateTextureSamplingMode(samplingMode, texture);
  13150. this._internalTexturesCache.push(texture);
  13151. return texture;
  13152. };
  13153. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13154. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13155. if (texture.isCube) {
  13156. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13157. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13158. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13160. }
  13161. else if (texture.is3D) {
  13162. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13165. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13166. }
  13167. else {
  13168. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13170. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13171. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13172. }
  13173. texture.samplingMode = samplingMode;
  13174. };
  13175. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13176. if (premulAlpha === void 0) { premulAlpha = false; }
  13177. if (!texture) {
  13178. return;
  13179. }
  13180. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13181. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13182. if (premulAlpha) {
  13183. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13184. }
  13185. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13187. if (texture.generateMipMaps) {
  13188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13189. }
  13190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13191. if (premulAlpha) {
  13192. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13193. }
  13194. texture.isReady = true;
  13195. };
  13196. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13197. if (!texture || texture._isDisabled) {
  13198. return;
  13199. }
  13200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13201. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13202. try {
  13203. // Testing video texture support
  13204. if (this._videoTextureSupported === undefined) {
  13205. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13206. if (this._gl.getError() !== 0) {
  13207. this._videoTextureSupported = false;
  13208. }
  13209. else {
  13210. this._videoTextureSupported = true;
  13211. }
  13212. }
  13213. // Copy video through the current working canvas if video texture is not supported
  13214. if (!this._videoTextureSupported) {
  13215. if (!texture._workingCanvas) {
  13216. texture._workingCanvas = document.createElement("canvas");
  13217. var context = texture._workingCanvas.getContext("2d");
  13218. if (!context) {
  13219. throw new Error("Unable to get 2d context");
  13220. }
  13221. texture._workingContext = context;
  13222. texture._workingCanvas.width = texture.width;
  13223. texture._workingCanvas.height = texture.height;
  13224. }
  13225. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13227. }
  13228. else {
  13229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13230. }
  13231. if (texture.generateMipMaps) {
  13232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13233. }
  13234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13235. // this.resetTextureCache();
  13236. texture.isReady = true;
  13237. }
  13238. catch (ex) {
  13239. // Something unexpected
  13240. // Let's disable the texture
  13241. texture._isDisabled = true;
  13242. }
  13243. };
  13244. /**
  13245. * Updates a depth texture Comparison Mode and Function.
  13246. * If the comparison Function is equal to 0, the mode will be set to none.
  13247. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13248. * @param texture The texture to set the comparison function for
  13249. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13250. */
  13251. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13252. if (this.webGLVersion === 1) {
  13253. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13254. return;
  13255. }
  13256. var gl = this._gl;
  13257. if (texture.isCube) {
  13258. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13259. if (comparisonFunction === 0) {
  13260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13262. }
  13263. else {
  13264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13266. }
  13267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13268. }
  13269. else {
  13270. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13271. if (comparisonFunction === 0) {
  13272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13274. }
  13275. else {
  13276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13278. }
  13279. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13280. }
  13281. texture._comparisonFunction = comparisonFunction;
  13282. };
  13283. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13284. var width = size.width || size;
  13285. var height = size.height || size;
  13286. internalTexture.baseWidth = width;
  13287. internalTexture.baseHeight = height;
  13288. internalTexture.width = width;
  13289. internalTexture.height = height;
  13290. internalTexture.isReady = true;
  13291. internalTexture.samples = 1;
  13292. internalTexture.generateMipMaps = false;
  13293. internalTexture._generateDepthBuffer = true;
  13294. internalTexture._generateStencilBuffer = generateStencil;
  13295. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13296. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13297. internalTexture._comparisonFunction = comparisonFunction;
  13298. var gl = this._gl;
  13299. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13300. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13301. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13302. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13303. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13304. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13305. if (comparisonFunction === 0) {
  13306. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13307. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13308. }
  13309. else {
  13310. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13311. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13312. }
  13313. };
  13314. /**
  13315. * Creates a depth stencil texture.
  13316. * This is only available in WebGL 2 or with the depth texture extension available.
  13317. * @param size The size of face edge in the texture.
  13318. * @param options The options defining the texture.
  13319. * @returns The texture
  13320. */
  13321. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13322. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13323. if (!this._caps.depthTextureExtension) {
  13324. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13325. return internalTexture;
  13326. }
  13327. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13328. var gl = this._gl;
  13329. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13330. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13331. if (this.webGLVersion > 1) {
  13332. if (internalOptions.generateStencil) {
  13333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13334. }
  13335. else {
  13336. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13337. }
  13338. }
  13339. else {
  13340. if (internalOptions.generateStencil) {
  13341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13342. }
  13343. else {
  13344. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13345. }
  13346. }
  13347. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13348. return internalTexture;
  13349. };
  13350. /**
  13351. * Creates a depth stencil cube texture.
  13352. * This is only available in WebGL 2.
  13353. * @param size The size of face edge in the cube texture.
  13354. * @param options The options defining the cube texture.
  13355. * @returns The cube texture
  13356. */
  13357. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13358. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13359. internalTexture.isCube = true;
  13360. if (this.webGLVersion === 1) {
  13361. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13362. return internalTexture;
  13363. }
  13364. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13365. var gl = this._gl;
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13367. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13368. // Create the depth/stencil buffer
  13369. for (var face = 0; face < 6; face++) {
  13370. if (internalOptions.generateStencil) {
  13371. 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);
  13372. }
  13373. else {
  13374. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13375. }
  13376. }
  13377. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13378. return internalTexture;
  13379. };
  13380. /**
  13381. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13382. * @param renderTarget The render target to set the frame buffer for
  13383. */
  13384. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13385. // Create the framebuffer
  13386. var internalTexture = renderTarget.getInternalTexture();
  13387. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13388. return;
  13389. }
  13390. var gl = this._gl;
  13391. var depthStencilTexture = renderTarget.depthStencilTexture;
  13392. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13393. if (depthStencilTexture.isCube) {
  13394. if (depthStencilTexture._generateStencilBuffer) {
  13395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13396. }
  13397. else {
  13398. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13399. }
  13400. }
  13401. else {
  13402. if (depthStencilTexture._generateStencilBuffer) {
  13403. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13404. }
  13405. else {
  13406. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13407. }
  13408. }
  13409. this.bindUnboundFramebuffer(null);
  13410. };
  13411. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13412. var fullOptions = new RenderTargetCreationOptions();
  13413. if (options !== undefined && typeof options === "object") {
  13414. fullOptions.generateMipMaps = options.generateMipMaps;
  13415. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13416. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13417. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13418. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13419. }
  13420. else {
  13421. fullOptions.generateMipMaps = options;
  13422. fullOptions.generateDepthBuffer = true;
  13423. fullOptions.generateStencilBuffer = false;
  13424. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13425. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13426. }
  13427. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13428. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13429. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13430. }
  13431. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13432. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13433. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13434. }
  13435. var gl = this._gl;
  13436. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13437. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13438. var width = size.width || size;
  13439. var height = size.height || size;
  13440. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13441. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13442. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13443. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13444. }
  13445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13449. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13450. // Create the framebuffer
  13451. var framebuffer = gl.createFramebuffer();
  13452. this.bindUnboundFramebuffer(framebuffer);
  13453. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13454. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13455. if (fullOptions.generateMipMaps) {
  13456. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13457. }
  13458. // Unbind
  13459. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13461. this.bindUnboundFramebuffer(null);
  13462. texture._framebuffer = framebuffer;
  13463. texture.baseWidth = width;
  13464. texture.baseHeight = height;
  13465. texture.width = width;
  13466. texture.height = height;
  13467. texture.isReady = true;
  13468. texture.samples = 1;
  13469. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13470. texture.samplingMode = fullOptions.samplingMode;
  13471. texture.type = fullOptions.type;
  13472. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13473. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13474. // this.resetTextureCache();
  13475. this._internalTexturesCache.push(texture);
  13476. return texture;
  13477. };
  13478. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13479. var generateMipMaps = false;
  13480. var generateDepthBuffer = true;
  13481. var generateStencilBuffer = false;
  13482. var generateDepthTexture = false;
  13483. var textureCount = 1;
  13484. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13485. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13486. var types = [], samplingModes = [];
  13487. if (options !== undefined) {
  13488. generateMipMaps = options.generateMipMaps;
  13489. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13490. generateStencilBuffer = options.generateStencilBuffer;
  13491. generateDepthTexture = options.generateDepthTexture;
  13492. textureCount = options.textureCount || 1;
  13493. if (options.types) {
  13494. types = options.types;
  13495. }
  13496. if (options.samplingModes) {
  13497. samplingModes = options.samplingModes;
  13498. }
  13499. }
  13500. var gl = this._gl;
  13501. // Create the framebuffer
  13502. var framebuffer = gl.createFramebuffer();
  13503. this.bindUnboundFramebuffer(framebuffer);
  13504. var width = size.width || size;
  13505. var height = size.height || size;
  13506. var textures = [];
  13507. var attachments = [];
  13508. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13509. for (var i = 0; i < textureCount; i++) {
  13510. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13511. var type = types[i] || defaultType;
  13512. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13513. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13514. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13515. }
  13516. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13517. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13518. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13519. }
  13520. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13521. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13522. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13523. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13524. }
  13525. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13526. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13527. textures.push(texture);
  13528. attachments.push(attachment);
  13529. gl.activeTexture(gl["TEXTURE" + i]);
  13530. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13535. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13536. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13537. if (generateMipMaps) {
  13538. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13539. }
  13540. // Unbind
  13541. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13542. texture._framebuffer = framebuffer;
  13543. texture._depthStencilBuffer = depthStencilBuffer;
  13544. texture.baseWidth = width;
  13545. texture.baseHeight = height;
  13546. texture.width = width;
  13547. texture.height = height;
  13548. texture.isReady = true;
  13549. texture.samples = 1;
  13550. texture.generateMipMaps = generateMipMaps;
  13551. texture.samplingMode = samplingMode;
  13552. texture.type = type;
  13553. texture._generateDepthBuffer = generateDepthBuffer;
  13554. texture._generateStencilBuffer = generateStencilBuffer;
  13555. texture._attachments = attachments;
  13556. this._internalTexturesCache.push(texture);
  13557. }
  13558. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13559. // Depth texture
  13560. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13561. gl.activeTexture(gl.TEXTURE0);
  13562. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13567. 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);
  13568. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13569. depthTexture._framebuffer = framebuffer;
  13570. depthTexture.baseWidth = width;
  13571. depthTexture.baseHeight = height;
  13572. depthTexture.width = width;
  13573. depthTexture.height = height;
  13574. depthTexture.isReady = true;
  13575. depthTexture.samples = 1;
  13576. depthTexture.generateMipMaps = generateMipMaps;
  13577. depthTexture.samplingMode = gl.NEAREST;
  13578. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13579. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13580. textures.push(depthTexture);
  13581. this._internalTexturesCache.push(depthTexture);
  13582. }
  13583. gl.drawBuffers(attachments);
  13584. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13585. this.bindUnboundFramebuffer(null);
  13586. this.resetTextureCache();
  13587. return textures;
  13588. };
  13589. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13590. if (samples === void 0) { samples = 1; }
  13591. var depthStencilBuffer = null;
  13592. var gl = this._gl;
  13593. // Create the depth/stencil buffer
  13594. if (generateStencilBuffer) {
  13595. depthStencilBuffer = gl.createRenderbuffer();
  13596. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13597. if (samples > 1) {
  13598. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13599. }
  13600. else {
  13601. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13602. }
  13603. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13604. }
  13605. else if (generateDepthBuffer) {
  13606. depthStencilBuffer = gl.createRenderbuffer();
  13607. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13608. if (samples > 1) {
  13609. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13610. }
  13611. else {
  13612. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13613. }
  13614. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13615. }
  13616. return depthStencilBuffer;
  13617. };
  13618. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13619. if (this.webGLVersion < 2 || !texture) {
  13620. return 1;
  13621. }
  13622. if (texture.samples === samples) {
  13623. return samples;
  13624. }
  13625. var gl = this._gl;
  13626. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13627. // Dispose previous render buffers
  13628. if (texture._depthStencilBuffer) {
  13629. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13630. texture._depthStencilBuffer = null;
  13631. }
  13632. if (texture._MSAAFramebuffer) {
  13633. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13634. texture._MSAAFramebuffer = null;
  13635. }
  13636. if (texture._MSAARenderBuffer) {
  13637. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13638. texture._MSAARenderBuffer = null;
  13639. }
  13640. if (samples > 1) {
  13641. var framebuffer = gl.createFramebuffer();
  13642. if (!framebuffer) {
  13643. throw new Error("Unable to create multi sampled framebuffer");
  13644. }
  13645. texture._MSAAFramebuffer = framebuffer;
  13646. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13647. var colorRenderbuffer = gl.createRenderbuffer();
  13648. if (!colorRenderbuffer) {
  13649. throw new Error("Unable to create multi sampled framebuffer");
  13650. }
  13651. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13652. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13654. texture._MSAARenderBuffer = colorRenderbuffer;
  13655. }
  13656. else {
  13657. this.bindUnboundFramebuffer(texture._framebuffer);
  13658. }
  13659. texture.samples = samples;
  13660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. return samples;
  13664. };
  13665. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13666. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13667. return 1;
  13668. }
  13669. if (textures[0].samples === samples) {
  13670. return samples;
  13671. }
  13672. var gl = this._gl;
  13673. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13674. // Dispose previous render buffers
  13675. if (textures[0]._depthStencilBuffer) {
  13676. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13677. textures[0]._depthStencilBuffer = null;
  13678. }
  13679. if (textures[0]._MSAAFramebuffer) {
  13680. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13681. textures[0]._MSAAFramebuffer = null;
  13682. }
  13683. for (var i = 0; i < textures.length; i++) {
  13684. if (textures[i]._MSAARenderBuffer) {
  13685. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13686. textures[i]._MSAARenderBuffer = null;
  13687. }
  13688. }
  13689. if (samples > 1) {
  13690. var framebuffer = gl.createFramebuffer();
  13691. if (!framebuffer) {
  13692. throw new Error("Unable to create multi sampled framebuffer");
  13693. }
  13694. this.bindUnboundFramebuffer(framebuffer);
  13695. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13696. var attachments = [];
  13697. for (var i = 0; i < textures.length; i++) {
  13698. var texture = textures[i];
  13699. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13700. var colorRenderbuffer = gl.createRenderbuffer();
  13701. if (!colorRenderbuffer) {
  13702. throw new Error("Unable to create multi sampled framebuffer");
  13703. }
  13704. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13705. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13706. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13707. texture._MSAAFramebuffer = framebuffer;
  13708. texture._MSAARenderBuffer = colorRenderbuffer;
  13709. texture.samples = samples;
  13710. texture._depthStencilBuffer = depthStencilBuffer;
  13711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13712. attachments.push(attachment);
  13713. }
  13714. gl.drawBuffers(attachments);
  13715. }
  13716. else {
  13717. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13718. }
  13719. this.bindUnboundFramebuffer(null);
  13720. return samples;
  13721. };
  13722. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13723. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13724. };
  13725. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13726. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13727. };
  13728. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13729. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13730. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13731. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13732. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13733. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13734. }
  13735. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13736. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13737. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13738. }
  13739. var gl = this._gl;
  13740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13741. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13742. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13744. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13745. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13746. }
  13747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13751. for (var face = 0; face < 6; face++) {
  13752. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13753. }
  13754. // Create the framebuffer
  13755. var framebuffer = gl.createFramebuffer();
  13756. this.bindUnboundFramebuffer(framebuffer);
  13757. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13758. // MipMaps
  13759. if (fullOptions.generateMipMaps) {
  13760. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13761. }
  13762. // Unbind
  13763. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. texture._framebuffer = framebuffer;
  13767. texture.width = size;
  13768. texture.height = size;
  13769. texture.isReady = true;
  13770. texture.isCube = true;
  13771. texture.samples = 1;
  13772. texture.generateMipMaps = fullOptions.generateMipMaps;
  13773. texture.samplingMode = fullOptions.samplingMode;
  13774. texture.type = fullOptions.type;
  13775. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13776. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13777. this._internalTexturesCache.push(texture);
  13778. return texture;
  13779. };
  13780. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13781. var _this = this;
  13782. if (onLoad === void 0) { onLoad = null; }
  13783. if (onError === void 0) { onError = null; }
  13784. if (forcedExtension === void 0) { forcedExtension = null; }
  13785. var callback = function (loadData) {
  13786. if (!loadData) {
  13787. if (onLoad) {
  13788. onLoad(null);
  13789. }
  13790. return;
  13791. }
  13792. var texture = loadData.texture;
  13793. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13794. texture._lodGenerationScale = scale;
  13795. texture._lodGenerationOffset = offset;
  13796. if (_this._caps.textureLOD) {
  13797. // Do not add extra process if texture lod is supported.
  13798. if (onLoad) {
  13799. onLoad(texture);
  13800. }
  13801. return;
  13802. }
  13803. var mipSlices = 3;
  13804. var gl = _this._gl;
  13805. var width = loadData.width;
  13806. if (!width) {
  13807. return;
  13808. }
  13809. var textures = [];
  13810. for (var i = 0; i < mipSlices; i++) {
  13811. //compute LOD from even spacing in smoothness (matching shader calculation)
  13812. var smoothness = i / (mipSlices - 1);
  13813. var roughness = 1 - smoothness;
  13814. var minLODIndex = offset; // roughness = 0
  13815. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13816. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13817. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13818. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13819. glTextureFromLod.isCube = true;
  13820. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13825. if (loadData.isDDS) {
  13826. var info = loadData.info;
  13827. var data = loadData.data;
  13828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13829. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13830. }
  13831. else {
  13832. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13833. }
  13834. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13835. // Wrap in a base texture for easy binding.
  13836. var lodTexture = new BABYLON.BaseTexture(scene);
  13837. lodTexture.isCube = true;
  13838. lodTexture._texture = glTextureFromLod;
  13839. glTextureFromLod.isReady = true;
  13840. textures.push(lodTexture);
  13841. }
  13842. texture._lodTextureHigh = textures[2];
  13843. texture._lodTextureMid = textures[1];
  13844. texture._lodTextureLow = textures[0];
  13845. if (onLoad) {
  13846. onLoad(texture);
  13847. }
  13848. };
  13849. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13850. };
  13851. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13852. var _this = this;
  13853. if (onLoad === void 0) { onLoad = null; }
  13854. if (onError === void 0) { onError = null; }
  13855. if (forcedExtension === void 0) { forcedExtension = null; }
  13856. var gl = this._gl;
  13857. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13858. texture.isCube = true;
  13859. texture.url = rootUrl;
  13860. texture.generateMipMaps = !noMipmap;
  13861. if (!this._doNotHandleContextLost) {
  13862. texture._extension = forcedExtension;
  13863. texture._files = files;
  13864. }
  13865. var isKTX = false;
  13866. var isDDS = false;
  13867. var lastDot = rootUrl.lastIndexOf('.');
  13868. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13869. if (this._textureFormatInUse) {
  13870. extension = this._textureFormatInUse;
  13871. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13872. isKTX = true;
  13873. }
  13874. else {
  13875. isDDS = (extension === ".dds");
  13876. }
  13877. var onerror = function (request, exception) {
  13878. if (onError && request) {
  13879. onError(request.status + " " + request.statusText, exception);
  13880. }
  13881. };
  13882. if (isKTX) {
  13883. this._loadFile(rootUrl, function (data) {
  13884. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13885. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13888. ktx.uploadLevels(_this._gl, !noMipmap);
  13889. _this.setCubeMapTextureParams(gl, loadMipmap);
  13890. texture.width = ktx.pixelWidth;
  13891. texture.height = ktx.pixelHeight;
  13892. texture.isReady = true;
  13893. }, undefined, undefined, true, onerror);
  13894. }
  13895. else if (isDDS) {
  13896. if (files && files.length === 6) {
  13897. this._cascadeLoadFiles(scene, function (imgs) {
  13898. var info;
  13899. var loadMipmap = false;
  13900. var width = 0;
  13901. for (var index = 0; index < imgs.length; index++) {
  13902. var data = imgs[index];
  13903. info = BABYLON.DDSTools.GetDDSInfo(data);
  13904. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13907. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13908. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13910. }
  13911. texture.width = info.width;
  13912. texture.height = info.height;
  13913. texture.type = info.textureType;
  13914. width = info.width;
  13915. }
  13916. _this.setCubeMapTextureParams(gl, loadMipmap);
  13917. texture.isReady = true;
  13918. if (onLoad) {
  13919. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13920. }
  13921. }, files, onError);
  13922. }
  13923. else {
  13924. this._loadFile(rootUrl, function (data) {
  13925. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13926. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13927. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13929. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13930. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13932. }
  13933. _this.setCubeMapTextureParams(gl, loadMipmap);
  13934. texture.width = info.width;
  13935. texture.height = info.height;
  13936. texture.isReady = true;
  13937. texture.type = info.textureType;
  13938. if (onLoad) {
  13939. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13940. }
  13941. }, undefined, undefined, true, onerror);
  13942. }
  13943. }
  13944. else {
  13945. if (!files) {
  13946. throw new Error("Cannot load cubemap because files were not defined");
  13947. }
  13948. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13949. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13950. var height = width;
  13951. _this._prepareWorkingCanvas();
  13952. if (!_this._workingCanvas || !_this._workingContext) {
  13953. return;
  13954. }
  13955. _this._workingCanvas.width = width;
  13956. _this._workingCanvas.height = height;
  13957. var faces = [
  13958. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13959. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13960. ];
  13961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13963. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13964. for (var index = 0; index < faces.length; index++) {
  13965. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13966. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13967. }
  13968. if (!noMipmap) {
  13969. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13970. }
  13971. _this.setCubeMapTextureParams(gl, !noMipmap);
  13972. texture.width = width;
  13973. texture.height = height;
  13974. texture.isReady = true;
  13975. if (format) {
  13976. texture.format = format;
  13977. }
  13978. texture.onLoadedObservable.notifyObservers(texture);
  13979. texture.onLoadedObservable.clear();
  13980. if (onLoad) {
  13981. onLoad();
  13982. }
  13983. }, files, onError);
  13984. }
  13985. this._internalTexturesCache.push(texture);
  13986. return texture;
  13987. };
  13988. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13991. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13993. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13994. // this.resetTextureCache();
  13995. };
  13996. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13997. if (compression === void 0) { compression = null; }
  13998. if (level === void 0) { level = 0; }
  13999. texture._bufferViewArray = data;
  14000. texture.format = format;
  14001. texture.type = type;
  14002. texture.invertY = invertY;
  14003. texture._compression = compression;
  14004. var gl = this._gl;
  14005. var textureType = this._getWebGLTextureType(type);
  14006. var internalFormat = this._getInternalFormat(format);
  14007. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14008. var needConversion = false;
  14009. if (internalFormat === gl.RGB) {
  14010. internalFormat = gl.RGBA;
  14011. needConversion = true;
  14012. }
  14013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14014. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14015. if (texture.width % 4 !== 0) {
  14016. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14017. }
  14018. // Data are known to be in +X +Y +Z -X -Y -Z
  14019. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14020. var faceData = data[faceIndex];
  14021. if (compression) {
  14022. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14023. }
  14024. else {
  14025. if (needConversion) {
  14026. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14027. }
  14028. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14029. }
  14030. }
  14031. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14032. if (isPot && texture.generateMipMaps && level === 0) {
  14033. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14034. }
  14035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14036. // this.resetTextureCache();
  14037. texture.isReady = true;
  14038. };
  14039. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14040. if (compression === void 0) { compression = null; }
  14041. var gl = this._gl;
  14042. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14043. texture.isCube = true;
  14044. texture.generateMipMaps = generateMipMaps;
  14045. texture.format = format;
  14046. texture.type = type;
  14047. if (!this._doNotHandleContextLost) {
  14048. texture._bufferViewArray = data;
  14049. }
  14050. var textureType = this._getWebGLTextureType(type);
  14051. var internalFormat = this._getInternalFormat(format);
  14052. if (internalFormat === gl.RGB) {
  14053. internalFormat = gl.RGBA;
  14054. }
  14055. var width = size;
  14056. var height = width;
  14057. texture.width = width;
  14058. texture.height = height;
  14059. // Double check on POT to generate Mips.
  14060. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14061. if (!isPot) {
  14062. generateMipMaps = false;
  14063. }
  14064. // Upload data if needed. The texture won't be ready until then.
  14065. if (data) {
  14066. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14067. }
  14068. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14069. // Filters
  14070. if (data && generateMipMaps) {
  14071. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14072. }
  14073. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14076. }
  14077. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14080. }
  14081. else {
  14082. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14085. }
  14086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14088. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14089. return texture;
  14090. };
  14091. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14092. var _this = this;
  14093. if (onLoad === void 0) { onLoad = null; }
  14094. if (onError === void 0) { onError = null; }
  14095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14096. if (invertY === void 0) { invertY = false; }
  14097. var gl = this._gl;
  14098. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14099. scene._addPendingData(texture);
  14100. texture.url = url;
  14101. this._internalTexturesCache.push(texture);
  14102. var onerror = function (request, exception) {
  14103. scene._removePendingData(texture);
  14104. if (onError && request) {
  14105. onError(request.status + " " + request.statusText, exception);
  14106. }
  14107. };
  14108. var internalCallback = function (data) {
  14109. var width = texture.width;
  14110. var faceDataArrays = callback(data);
  14111. if (!faceDataArrays) {
  14112. return;
  14113. }
  14114. if (mipmmapGenerator) {
  14115. var textureType = _this._getWebGLTextureType(type);
  14116. var internalFormat = _this._getInternalFormat(format);
  14117. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14118. var needConversion = false;
  14119. if (internalFormat === gl.RGB) {
  14120. internalFormat = gl.RGBA;
  14121. needConversion = true;
  14122. }
  14123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14124. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14125. var mipData = mipmmapGenerator(faceDataArrays);
  14126. for (var level = 0; level < mipData.length; level++) {
  14127. var mipSize = width >> level;
  14128. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14129. var mipFaceData = mipData[level][faceIndex];
  14130. if (needConversion) {
  14131. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14132. }
  14133. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14134. }
  14135. }
  14136. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14137. }
  14138. else {
  14139. texture.generateMipMaps = !noMipmap;
  14140. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14141. }
  14142. texture.isReady = true;
  14143. // this.resetTextureCache();
  14144. scene._removePendingData(texture);
  14145. if (onLoad) {
  14146. onLoad();
  14147. }
  14148. };
  14149. this._loadFile(url, function (data) {
  14150. internalCallback(data);
  14151. }, undefined, scene.database, true, onerror);
  14152. return texture;
  14153. };
  14154. ;
  14155. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14156. if (compression === void 0) { compression = null; }
  14157. var internalFormat = this._getInternalFormat(format);
  14158. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14160. if (!this._doNotHandleContextLost) {
  14161. texture._bufferView = data;
  14162. texture.format = format;
  14163. texture.invertY = invertY;
  14164. texture._compression = compression;
  14165. }
  14166. if (texture.width % 4 !== 0) {
  14167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14168. }
  14169. if (compression && data) {
  14170. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14171. }
  14172. else {
  14173. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14174. }
  14175. if (texture.generateMipMaps) {
  14176. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14177. }
  14178. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14179. // this.resetTextureCache();
  14180. texture.isReady = true;
  14181. };
  14182. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14183. if (compression === void 0) { compression = null; }
  14184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14185. texture.baseWidth = width;
  14186. texture.baseHeight = height;
  14187. texture.baseDepth = depth;
  14188. texture.width = width;
  14189. texture.height = height;
  14190. texture.depth = depth;
  14191. texture.format = format;
  14192. texture.generateMipMaps = generateMipMaps;
  14193. texture.samplingMode = samplingMode;
  14194. texture.is3D = true;
  14195. if (!this._doNotHandleContextLost) {
  14196. texture._bufferView = data;
  14197. }
  14198. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14200. // Filters
  14201. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14204. if (generateMipMaps) {
  14205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14206. }
  14207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14208. this._internalTexturesCache.push(texture);
  14209. return texture;
  14210. };
  14211. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14212. var gl = this._gl;
  14213. if (!gl) {
  14214. return;
  14215. }
  14216. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14219. if (!noMipmap && !isCompressed) {
  14220. gl.generateMipmap(gl.TEXTURE_2D);
  14221. }
  14222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14223. // this.resetTextureCache();
  14224. if (scene) {
  14225. scene._removePendingData(texture);
  14226. }
  14227. texture.onLoadedObservable.notifyObservers(texture);
  14228. texture.onLoadedObservable.clear();
  14229. };
  14230. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14231. var _this = this;
  14232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14233. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14234. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14235. var gl = this._gl;
  14236. if (!gl) {
  14237. return;
  14238. }
  14239. if (!texture._webGLTexture) {
  14240. // this.resetTextureCache();
  14241. if (scene) {
  14242. scene._removePendingData(texture);
  14243. }
  14244. return;
  14245. }
  14246. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14248. texture.baseWidth = width;
  14249. texture.baseHeight = height;
  14250. texture.width = potWidth;
  14251. texture.height = potHeight;
  14252. texture.isReady = true;
  14253. if (processFunction(potWidth, potHeight, function () {
  14254. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14255. })) {
  14256. // Returning as texture needs extra async steps
  14257. return;
  14258. }
  14259. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14260. };
  14261. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14262. // Create new RGBA data container.
  14263. var rgbaData;
  14264. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14265. rgbaData = new Float32Array(width * height * 4);
  14266. }
  14267. else {
  14268. rgbaData = new Uint32Array(width * height * 4);
  14269. }
  14270. // Convert each pixel.
  14271. for (var x = 0; x < width; x++) {
  14272. for (var y = 0; y < height; y++) {
  14273. var index = (y * width + x) * 3;
  14274. var newIndex = (y * width + x) * 4;
  14275. // Map Old Value to new value.
  14276. rgbaData[newIndex + 0] = rgbData[index + 0];
  14277. rgbaData[newIndex + 1] = rgbData[index + 1];
  14278. rgbaData[newIndex + 2] = rgbData[index + 2];
  14279. // Add fully opaque alpha channel.
  14280. rgbaData[newIndex + 3] = 1;
  14281. }
  14282. }
  14283. return rgbaData;
  14284. };
  14285. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14286. var gl = this._gl;
  14287. if (texture._framebuffer) {
  14288. gl.deleteFramebuffer(texture._framebuffer);
  14289. texture._framebuffer = null;
  14290. }
  14291. if (texture._depthStencilBuffer) {
  14292. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14293. texture._depthStencilBuffer = null;
  14294. }
  14295. if (texture._MSAAFramebuffer) {
  14296. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14297. texture._MSAAFramebuffer = null;
  14298. }
  14299. if (texture._MSAARenderBuffer) {
  14300. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14301. texture._MSAARenderBuffer = null;
  14302. }
  14303. };
  14304. Engine.prototype._releaseTexture = function (texture) {
  14305. var gl = this._gl;
  14306. this._releaseFramebufferObjects(texture);
  14307. gl.deleteTexture(texture._webGLTexture);
  14308. // Unbind channels
  14309. this.unbindAllTextures();
  14310. var index = this._internalTexturesCache.indexOf(texture);
  14311. if (index !== -1) {
  14312. this._internalTexturesCache.splice(index, 1);
  14313. }
  14314. // Integrated fixed lod samplers.
  14315. if (texture._lodTextureHigh) {
  14316. texture._lodTextureHigh.dispose();
  14317. }
  14318. if (texture._lodTextureMid) {
  14319. texture._lodTextureMid.dispose();
  14320. }
  14321. if (texture._lodTextureLow) {
  14322. texture._lodTextureLow.dispose();
  14323. }
  14324. };
  14325. Engine.prototype.setProgram = function (program) {
  14326. if (this._currentProgram !== program) {
  14327. this._gl.useProgram(program);
  14328. this._currentProgram = program;
  14329. }
  14330. };
  14331. Engine.prototype.bindSamplers = function (effect) {
  14332. this.setProgram(effect.getProgram());
  14333. var samplers = effect.getSamplers();
  14334. for (var index = 0; index < samplers.length; index++) {
  14335. var uniform = effect.getUniform(samplers[index]);
  14336. if (uniform) {
  14337. this._boundUniforms[index] = uniform;
  14338. }
  14339. }
  14340. this._currentEffect = null;
  14341. };
  14342. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14343. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14344. return;
  14345. }
  14346. // Remove
  14347. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14348. // Bind last to it
  14349. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14350. // Bind to dummy
  14351. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14352. };
  14353. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14354. if (!internalTexture) {
  14355. return -1;
  14356. }
  14357. internalTexture._initialSlot = channel;
  14358. if (this.disableTextureBindingOptimization) {
  14359. if (channel !== internalTexture._designatedSlot) {
  14360. this._textureCollisions.addCount(1, false);
  14361. }
  14362. }
  14363. else {
  14364. if (channel !== internalTexture._designatedSlot) {
  14365. if (internalTexture._designatedSlot > -1) {
  14366. return internalTexture._designatedSlot;
  14367. }
  14368. else {
  14369. // No slot for this texture, let's pick a new one (if we find a free slot)
  14370. if (this._nextFreeTextureSlots.length) {
  14371. return this._nextFreeTextureSlots[0];
  14372. }
  14373. // We need to recycle the oldest bound texture, sorry.
  14374. this._textureCollisions.addCount(1, false);
  14375. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14376. }
  14377. }
  14378. }
  14379. return channel;
  14380. };
  14381. Engine.prototype._linkTrackers = function (previous, next) {
  14382. previous.next = next;
  14383. next.previous = previous;
  14384. };
  14385. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14386. var currentSlot = internalTexture._designatedSlot;
  14387. if (currentSlot === -1) {
  14388. return -1;
  14389. }
  14390. internalTexture._designatedSlot = -1;
  14391. if (this.disableTextureBindingOptimization) {
  14392. return -1;
  14393. }
  14394. // Remove from bound list
  14395. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14396. // Free the slot
  14397. this._boundTexturesCache[currentSlot] = null;
  14398. this._nextFreeTextureSlots.push(currentSlot);
  14399. return currentSlot;
  14400. };
  14401. Engine.prototype._activateCurrentTexture = function () {
  14402. if (this._currentTextureChannel !== this._activeChannel) {
  14403. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14404. this._currentTextureChannel = this._activeChannel;
  14405. }
  14406. };
  14407. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14408. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14409. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14410. this._activeChannel = texture._designatedSlot;
  14411. }
  14412. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14413. var isTextureForRendering = texture && texture._initialSlot > -1;
  14414. if (currentTextureBound !== texture) {
  14415. if (currentTextureBound) {
  14416. this._removeDesignatedSlot(currentTextureBound);
  14417. }
  14418. this._activateCurrentTexture();
  14419. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14420. this._boundTexturesCache[this._activeChannel] = texture;
  14421. if (texture) {
  14422. if (!this.disableTextureBindingOptimization) {
  14423. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14424. if (slotIndex > -1) {
  14425. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14426. }
  14427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14428. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14429. }
  14430. texture._designatedSlot = this._activeChannel;
  14431. }
  14432. }
  14433. else if (forTextureDataUpdate) {
  14434. this._activateCurrentTexture();
  14435. }
  14436. if (isTextureForRendering && !forTextureDataUpdate) {
  14437. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14438. }
  14439. };
  14440. Engine.prototype._bindTexture = function (channel, texture) {
  14441. if (channel < 0) {
  14442. return;
  14443. }
  14444. if (texture) {
  14445. channel = this._getCorrectTextureChannel(channel, texture);
  14446. }
  14447. this._activeChannel = channel;
  14448. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14449. };
  14450. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14451. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14452. };
  14453. Engine.prototype.unbindAllTextures = function () {
  14454. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14455. this._activeChannel = channel;
  14456. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14457. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14458. if (this.webGLVersion > 1) {
  14459. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14460. }
  14461. }
  14462. };
  14463. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14464. if (channel < 0) {
  14465. return;
  14466. }
  14467. if (uniform) {
  14468. this._boundUniforms[channel] = uniform;
  14469. }
  14470. this._setTexture(channel, texture);
  14471. };
  14472. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14473. var uniform = this._boundUniforms[sourceSlot];
  14474. if (uniform._currentState === destination) {
  14475. return;
  14476. }
  14477. this._gl.uniform1i(uniform, destination);
  14478. uniform._currentState = destination;
  14479. };
  14480. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14481. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14482. // Not ready?
  14483. if (!texture) {
  14484. if (this._boundTexturesCache[channel] != null) {
  14485. this._activeChannel = channel;
  14486. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14488. if (this.webGLVersion > 1) {
  14489. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14490. }
  14491. }
  14492. return false;
  14493. }
  14494. // Video
  14495. if (texture.video) {
  14496. this._activeChannel = channel;
  14497. texture.update();
  14498. }
  14499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14500. texture.delayLoad();
  14501. return false;
  14502. }
  14503. var internalTexture;
  14504. if (texture.isReady()) {
  14505. internalTexture = texture.getInternalTexture();
  14506. }
  14507. else if (texture.isCube) {
  14508. internalTexture = this.emptyCubeTexture;
  14509. }
  14510. else if (texture.is3D) {
  14511. internalTexture = this.emptyTexture3D;
  14512. }
  14513. else {
  14514. internalTexture = this.emptyTexture;
  14515. }
  14516. if (!isPartOfTextureArray) {
  14517. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14518. }
  14519. if (this._boundTexturesCache[channel] === internalTexture) {
  14520. this._moveBoundTextureOnTop(internalTexture);
  14521. if (!isPartOfTextureArray) {
  14522. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14523. }
  14524. return false;
  14525. }
  14526. this._activeChannel = channel;
  14527. if (internalTexture && internalTexture.is3D) {
  14528. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14529. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14530. internalTexture._cachedWrapU = texture.wrapU;
  14531. switch (texture.wrapU) {
  14532. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14533. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14534. break;
  14535. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14537. break;
  14538. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14540. break;
  14541. }
  14542. }
  14543. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14544. internalTexture._cachedWrapV = texture.wrapV;
  14545. switch (texture.wrapV) {
  14546. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14547. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14548. break;
  14549. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14550. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14551. break;
  14552. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14553. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14554. break;
  14555. }
  14556. }
  14557. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14558. internalTexture._cachedWrapR = texture.wrapR;
  14559. switch (texture.wrapR) {
  14560. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14561. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14562. break;
  14563. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14564. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14565. break;
  14566. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14567. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14568. break;
  14569. }
  14570. }
  14571. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14572. }
  14573. else if (internalTexture && internalTexture.isCube) {
  14574. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14575. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14576. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14577. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14578. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14579. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14580. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14581. }
  14582. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14583. }
  14584. else {
  14585. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14586. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14587. internalTexture._cachedWrapU = texture.wrapU;
  14588. switch (texture.wrapU) {
  14589. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14590. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14591. break;
  14592. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14593. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14594. break;
  14595. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14597. break;
  14598. }
  14599. }
  14600. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14601. internalTexture._cachedWrapV = texture.wrapV;
  14602. switch (texture.wrapV) {
  14603. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14604. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14605. break;
  14606. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14608. break;
  14609. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14611. break;
  14612. }
  14613. }
  14614. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14615. }
  14616. return true;
  14617. };
  14618. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14619. if (channel < 0 || !uniform) {
  14620. return;
  14621. }
  14622. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14623. this._textureUnits = new Int32Array(textures.length);
  14624. }
  14625. for (var i = 0; i < textures.length; i++) {
  14626. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14627. }
  14628. this._gl.uniform1iv(uniform, this._textureUnits);
  14629. for (var index = 0; index < textures.length; index++) {
  14630. this._setTexture(this._textureUnits[index], textures[index], true);
  14631. }
  14632. };
  14633. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14634. var internalTexture = texture.getInternalTexture();
  14635. if (!internalTexture) {
  14636. return;
  14637. }
  14638. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14639. var value = texture.anisotropicFilteringLevel;
  14640. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14641. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14642. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14643. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14644. }
  14645. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14646. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14647. internalTexture._cachedAnisotropicFilteringLevel = value;
  14648. }
  14649. };
  14650. Engine.prototype.readPixels = function (x, y, width, height) {
  14651. var data = new Uint8Array(height * width * 4);
  14652. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14653. return data;
  14654. };
  14655. /**
  14656. * Add an externaly attached data from its key.
  14657. * This method call will fail and return false, if such key already exists.
  14658. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14659. * @param key the unique key that identifies the data
  14660. * @param data the data object to associate to the key for this Engine instance
  14661. * @return true if no such key were already present and the data was added successfully, false otherwise
  14662. */
  14663. Engine.prototype.addExternalData = function (key, data) {
  14664. if (!this._externalData) {
  14665. this._externalData = new BABYLON.StringDictionary();
  14666. }
  14667. return this._externalData.add(key, data);
  14668. };
  14669. /**
  14670. * Get an externaly attached data from its key
  14671. * @param key the unique key that identifies the data
  14672. * @return the associated data, if present (can be null), or undefined if not present
  14673. */
  14674. Engine.prototype.getExternalData = function (key) {
  14675. if (!this._externalData) {
  14676. this._externalData = new BABYLON.StringDictionary();
  14677. }
  14678. return this._externalData.get(key);
  14679. };
  14680. /**
  14681. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14682. * @param key the unique key that identifies the data
  14683. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14684. * @return the associated data, can be null if the factory returned null.
  14685. */
  14686. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14687. if (!this._externalData) {
  14688. this._externalData = new BABYLON.StringDictionary();
  14689. }
  14690. return this._externalData.getOrAddWithFactory(key, factory);
  14691. };
  14692. /**
  14693. * Remove an externaly attached data from the Engine instance
  14694. * @param key the unique key that identifies the data
  14695. * @return true if the data was successfully removed, false if it doesn't exist
  14696. */
  14697. Engine.prototype.removeExternalData = function (key) {
  14698. if (!this._externalData) {
  14699. this._externalData = new BABYLON.StringDictionary();
  14700. }
  14701. return this._externalData.remove(key);
  14702. };
  14703. Engine.prototype.unbindAllAttributes = function () {
  14704. if (this._mustWipeVertexAttributes) {
  14705. this._mustWipeVertexAttributes = false;
  14706. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14707. this._gl.disableVertexAttribArray(i);
  14708. this._vertexAttribArraysEnabled[i] = false;
  14709. this._currentBufferPointers[i].active = false;
  14710. }
  14711. return;
  14712. }
  14713. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14714. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14715. continue;
  14716. }
  14717. this._gl.disableVertexAttribArray(i);
  14718. this._vertexAttribArraysEnabled[i] = false;
  14719. this._currentBufferPointers[i].active = false;
  14720. }
  14721. };
  14722. Engine.prototype.releaseEffects = function () {
  14723. for (var name in this._compiledEffects) {
  14724. this._deleteProgram(this._compiledEffects[name]._program);
  14725. }
  14726. this._compiledEffects = {};
  14727. };
  14728. // Dispose
  14729. Engine.prototype.dispose = function () {
  14730. this.hideLoadingUI();
  14731. this.stopRenderLoop();
  14732. // Release postProcesses
  14733. while (this.postProcesses.length) {
  14734. this.postProcesses[0].dispose();
  14735. }
  14736. // Empty texture
  14737. if (this._emptyTexture) {
  14738. this._releaseTexture(this._emptyTexture);
  14739. this._emptyTexture = null;
  14740. }
  14741. if (this._emptyCubeTexture) {
  14742. this._releaseTexture(this._emptyCubeTexture);
  14743. this._emptyCubeTexture = null;
  14744. }
  14745. // Rescale PP
  14746. if (this._rescalePostProcess) {
  14747. this._rescalePostProcess.dispose();
  14748. }
  14749. // Release scenes
  14750. while (this.scenes.length) {
  14751. this.scenes[0].dispose();
  14752. }
  14753. // Release audio engine
  14754. if (Engine.audioEngine) {
  14755. Engine.audioEngine.dispose();
  14756. }
  14757. // Release effects
  14758. this.releaseEffects();
  14759. // Unbind
  14760. this.unbindAllAttributes();
  14761. if (this._dummyFramebuffer) {
  14762. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14763. }
  14764. //WebVR
  14765. this.disableVR();
  14766. // Events
  14767. if (BABYLON.Tools.IsWindowObjectExist()) {
  14768. window.removeEventListener("blur", this._onBlur);
  14769. window.removeEventListener("focus", this._onFocus);
  14770. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14771. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14772. if (this._renderingCanvas) {
  14773. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14774. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14775. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14776. if (!this._doNotHandleContextLost) {
  14777. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14778. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14779. }
  14780. }
  14781. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14782. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14783. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14784. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14785. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14786. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14787. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14788. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14789. if (this._onVrDisplayConnect) {
  14790. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14791. if (this._onVrDisplayDisconnect) {
  14792. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14793. }
  14794. if (this._onVrDisplayPresentChange) {
  14795. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14796. }
  14797. this._onVrDisplayConnect = null;
  14798. this._onVrDisplayDisconnect = null;
  14799. }
  14800. }
  14801. // Remove from Instances
  14802. var index = Engine.Instances.indexOf(this);
  14803. if (index >= 0) {
  14804. Engine.Instances.splice(index, 1);
  14805. }
  14806. this._workingCanvas = null;
  14807. this._workingContext = null;
  14808. this._currentBufferPointers = [];
  14809. this._renderingCanvas = null;
  14810. this._currentProgram = null;
  14811. this.onResizeObservable.clear();
  14812. this.onCanvasBlurObservable.clear();
  14813. this.onCanvasFocusObservable.clear();
  14814. this.onCanvasPointerOutObservable.clear();
  14815. this.onBeginFrameObservable.clear();
  14816. this.onEndFrameObservable.clear();
  14817. BABYLON.Effect.ResetCache();
  14818. // Abort active requests
  14819. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14820. var request = _a[_i];
  14821. request.abort();
  14822. }
  14823. };
  14824. // Loading screen
  14825. Engine.prototype.displayLoadingUI = function () {
  14826. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14827. return;
  14828. }
  14829. var loadingScreen = this.loadingScreen;
  14830. if (loadingScreen) {
  14831. loadingScreen.displayLoadingUI();
  14832. }
  14833. };
  14834. Engine.prototype.hideLoadingUI = function () {
  14835. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14836. return;
  14837. }
  14838. var loadingScreen = this.loadingScreen;
  14839. if (loadingScreen) {
  14840. loadingScreen.hideLoadingUI();
  14841. }
  14842. };
  14843. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14844. get: function () {
  14845. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14846. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14847. return this._loadingScreen;
  14848. },
  14849. set: function (loadingScreen) {
  14850. this._loadingScreen = loadingScreen;
  14851. },
  14852. enumerable: true,
  14853. configurable: true
  14854. });
  14855. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14856. set: function (text) {
  14857. this.loadingScreen.loadingUIText = text;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14863. set: function (color) {
  14864. this.loadingScreen.loadingUIBackgroundColor = color;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. Engine.prototype.attachContextLostEvent = function (callback) {
  14870. if (this._renderingCanvas) {
  14871. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14872. }
  14873. };
  14874. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14875. if (this._renderingCanvas) {
  14876. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14877. }
  14878. };
  14879. Engine.prototype.getVertexShaderSource = function (program) {
  14880. var shaders = this._gl.getAttachedShaders(program);
  14881. if (!shaders) {
  14882. return null;
  14883. }
  14884. return this._gl.getShaderSource(shaders[0]);
  14885. };
  14886. Engine.prototype.getFragmentShaderSource = function (program) {
  14887. var shaders = this._gl.getAttachedShaders(program);
  14888. if (!shaders) {
  14889. return null;
  14890. }
  14891. return this._gl.getShaderSource(shaders[1]);
  14892. };
  14893. Engine.prototype.getError = function () {
  14894. return this._gl.getError();
  14895. };
  14896. // FPS
  14897. Engine.prototype.getFps = function () {
  14898. return this._fps;
  14899. };
  14900. Engine.prototype.getDeltaTime = function () {
  14901. return this._deltaTime;
  14902. };
  14903. Engine.prototype._measureFps = function () {
  14904. this._performanceMonitor.sampleFrame();
  14905. this._fps = this._performanceMonitor.averageFPS;
  14906. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14907. };
  14908. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14909. if (faceIndex === void 0) { faceIndex = -1; }
  14910. var gl = this._gl;
  14911. if (!this._dummyFramebuffer) {
  14912. var dummy = gl.createFramebuffer();
  14913. if (!dummy) {
  14914. throw new Error("Unable to create dummy framebuffer");
  14915. }
  14916. this._dummyFramebuffer = dummy;
  14917. }
  14918. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14919. if (faceIndex > -1) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14924. }
  14925. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14926. var buffer;
  14927. switch (readType) {
  14928. case gl.UNSIGNED_BYTE:
  14929. buffer = new Uint8Array(4 * width * height);
  14930. readType = gl.UNSIGNED_BYTE;
  14931. break;
  14932. default:
  14933. buffer = new Float32Array(4 * width * height);
  14934. readType = gl.FLOAT;
  14935. break;
  14936. }
  14937. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14938. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14939. return buffer;
  14940. };
  14941. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14942. if (this._webGLVersion > 1) {
  14943. return this._caps.colorBufferFloat;
  14944. }
  14945. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14946. };
  14947. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14948. if (this._webGLVersion > 1) {
  14949. return this._caps.colorBufferFloat;
  14950. }
  14951. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14952. };
  14953. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14954. Engine.prototype._canRenderToFramebuffer = function (type) {
  14955. var gl = this._gl;
  14956. //clear existing errors
  14957. while (gl.getError() !== gl.NO_ERROR) { }
  14958. var successful = true;
  14959. var texture = gl.createTexture();
  14960. gl.bindTexture(gl.TEXTURE_2D, texture);
  14961. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14964. var fb = gl.createFramebuffer();
  14965. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14967. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14968. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14969. successful = successful && (gl.getError() === gl.NO_ERROR);
  14970. //try render by clearing frame buffer's color buffer
  14971. if (successful) {
  14972. gl.clear(gl.COLOR_BUFFER_BIT);
  14973. successful = successful && (gl.getError() === gl.NO_ERROR);
  14974. }
  14975. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14976. if (successful) {
  14977. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14978. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14979. var readFormat = gl.RGBA;
  14980. var readType = gl.UNSIGNED_BYTE;
  14981. var buffer = new Uint8Array(4);
  14982. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14983. successful = successful && (gl.getError() === gl.NO_ERROR);
  14984. }
  14985. //clean up
  14986. gl.deleteTexture(texture);
  14987. gl.deleteFramebuffer(fb);
  14988. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14989. //clear accumulated errors
  14990. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14991. return successful;
  14992. };
  14993. Engine.prototype._getWebGLTextureType = function (type) {
  14994. if (type === Engine.TEXTURETYPE_FLOAT) {
  14995. return this._gl.FLOAT;
  14996. }
  14997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14998. // Add Half Float Constant.
  14999. return this._gl.HALF_FLOAT_OES;
  15000. }
  15001. return this._gl.UNSIGNED_BYTE;
  15002. };
  15003. ;
  15004. /** @ignore */
  15005. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15006. if (this._webGLVersion === 1) {
  15007. return this._gl.RGBA;
  15008. }
  15009. if (type === Engine.TEXTURETYPE_FLOAT) {
  15010. if (format) {
  15011. switch (format) {
  15012. case Engine.TEXTUREFORMAT_R32F:
  15013. return this._gl.R32F;
  15014. case Engine.TEXTUREFORMAT_RG32F:
  15015. return this._gl.RG32F;
  15016. case Engine.TEXTUREFORMAT_RGB32F:
  15017. return this._gl.RGB32F;
  15018. }
  15019. }
  15020. return this._gl.RGBA32F;
  15021. }
  15022. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15023. return this._gl.RGBA16F;
  15024. }
  15025. return this._gl.RGBA;
  15026. };
  15027. ;
  15028. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15029. if (type === Engine.TEXTURETYPE_FLOAT) {
  15030. return this._gl.RGBA32F;
  15031. }
  15032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15033. return this._gl.RGBA16F;
  15034. }
  15035. return this._gl.RGBA8;
  15036. };
  15037. ;
  15038. Engine.prototype.createQuery = function () {
  15039. return this._gl.createQuery();
  15040. };
  15041. Engine.prototype.deleteQuery = function (query) {
  15042. this._gl.deleteQuery(query);
  15043. return this;
  15044. };
  15045. Engine.prototype.isQueryResultAvailable = function (query) {
  15046. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15047. };
  15048. Engine.prototype.getQueryResult = function (query) {
  15049. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15050. };
  15051. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15052. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15053. this._gl.beginQuery(glAlgorithm, query);
  15054. return this;
  15055. };
  15056. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15057. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15058. this._gl.endQuery(glAlgorithm);
  15059. return this;
  15060. };
  15061. /* Time queries */
  15062. Engine.prototype._createTimeQuery = function () {
  15063. var timerQuery = this._caps.timerQuery;
  15064. if (timerQuery.createQueryEXT) {
  15065. return timerQuery.createQueryEXT();
  15066. }
  15067. return this.createQuery();
  15068. };
  15069. Engine.prototype._deleteTimeQuery = function (query) {
  15070. var timerQuery = this._caps.timerQuery;
  15071. if (timerQuery.deleteQueryEXT) {
  15072. timerQuery.deleteQueryEXT(query);
  15073. return;
  15074. }
  15075. this.deleteQuery(query);
  15076. };
  15077. Engine.prototype._getTimeQueryResult = function (query) {
  15078. var timerQuery = this._caps.timerQuery;
  15079. if (timerQuery.getQueryObjectEXT) {
  15080. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15081. }
  15082. return this.getQueryResult(query);
  15083. };
  15084. Engine.prototype._getTimeQueryAvailability = function (query) {
  15085. var timerQuery = this._caps.timerQuery;
  15086. if (timerQuery.getQueryObjectEXT) {
  15087. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15088. }
  15089. return this.isQueryResultAvailable(query);
  15090. };
  15091. Engine.prototype.startTimeQuery = function () {
  15092. var timerQuery = this._caps.timerQuery;
  15093. if (!timerQuery) {
  15094. return null;
  15095. }
  15096. var token = new BABYLON._TimeToken();
  15097. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15098. if (this._caps.canUseTimestampForTimerQuery) {
  15099. token._startTimeQuery = this._createTimeQuery();
  15100. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15101. }
  15102. else {
  15103. if (this._currentNonTimestampToken) {
  15104. return this._currentNonTimestampToken;
  15105. }
  15106. token._timeElapsedQuery = this._createTimeQuery();
  15107. if (timerQuery.beginQueryEXT) {
  15108. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15109. }
  15110. else {
  15111. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15112. }
  15113. this._currentNonTimestampToken = token;
  15114. }
  15115. return token;
  15116. };
  15117. Engine.prototype.endTimeQuery = function (token) {
  15118. var timerQuery = this._caps.timerQuery;
  15119. if (!timerQuery || !token) {
  15120. return -1;
  15121. }
  15122. if (this._caps.canUseTimestampForTimerQuery) {
  15123. if (!token._startTimeQuery) {
  15124. return -1;
  15125. }
  15126. if (!token._endTimeQuery) {
  15127. token._endTimeQuery = this._createTimeQuery();
  15128. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15129. }
  15130. }
  15131. else if (!token._timeElapsedQueryEnded) {
  15132. if (!token._timeElapsedQuery) {
  15133. return -1;
  15134. }
  15135. if (timerQuery.endQueryEXT) {
  15136. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15137. }
  15138. else {
  15139. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15140. }
  15141. token._timeElapsedQueryEnded = true;
  15142. }
  15143. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15144. var available = false;
  15145. if (token._endTimeQuery) {
  15146. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15147. }
  15148. else if (token._timeElapsedQuery) {
  15149. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15150. }
  15151. if (available && !disjoint) {
  15152. var result = 0;
  15153. if (this._caps.canUseTimestampForTimerQuery) {
  15154. if (!token._startTimeQuery || !token._endTimeQuery) {
  15155. return -1;
  15156. }
  15157. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15158. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15159. result = timeEnd - timeStart;
  15160. this._deleteTimeQuery(token._startTimeQuery);
  15161. this._deleteTimeQuery(token._endTimeQuery);
  15162. token._startTimeQuery = null;
  15163. token._endTimeQuery = null;
  15164. }
  15165. else {
  15166. if (!token._timeElapsedQuery) {
  15167. return -1;
  15168. }
  15169. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15170. this._deleteTimeQuery(token._timeElapsedQuery);
  15171. token._timeElapsedQuery = null;
  15172. token._timeElapsedQueryEnded = false;
  15173. this._currentNonTimestampToken = null;
  15174. }
  15175. return result;
  15176. }
  15177. return -1;
  15178. };
  15179. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15180. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15181. };
  15182. // Transform feedback
  15183. Engine.prototype.createTransformFeedback = function () {
  15184. return this._gl.createTransformFeedback();
  15185. };
  15186. Engine.prototype.deleteTransformFeedback = function (value) {
  15187. this._gl.deleteTransformFeedback(value);
  15188. };
  15189. Engine.prototype.bindTransformFeedback = function (value) {
  15190. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15191. };
  15192. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15193. if (usePoints === void 0) { usePoints = true; }
  15194. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15195. };
  15196. Engine.prototype.endTransformFeedback = function () {
  15197. this._gl.endTransformFeedback();
  15198. };
  15199. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15200. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15201. };
  15202. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15203. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15204. };
  15205. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15206. var _this = this;
  15207. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15208. this._activeRequests.push(request);
  15209. request.onCompleteObservable.add(function (request) {
  15210. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15211. });
  15212. return request;
  15213. };
  15214. /** @ignore */
  15215. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15216. var _this = this;
  15217. return new Promise(function (resolve, reject) {
  15218. _this._loadFile(url, function (data) {
  15219. resolve(data);
  15220. }, undefined, database, useArrayBuffer, function (request, exception) {
  15221. reject(exception);
  15222. });
  15223. });
  15224. };
  15225. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15226. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15227. var onload = function (data) {
  15228. loadedFiles[index] = data;
  15229. loadedFiles._internalCount++;
  15230. if (loadedFiles._internalCount === 6) {
  15231. onfinish(loadedFiles);
  15232. }
  15233. };
  15234. var onerror = function (request, exception) {
  15235. if (onErrorCallBack && request) {
  15236. onErrorCallBack(request.status + " " + request.statusText, exception);
  15237. }
  15238. };
  15239. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15240. };
  15241. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15242. if (onError === void 0) { onError = null; }
  15243. var loadedFiles = [];
  15244. loadedFiles._internalCount = 0;
  15245. for (var index = 0; index < 6; index++) {
  15246. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15247. }
  15248. };
  15249. // Statics
  15250. Engine.isSupported = function () {
  15251. try {
  15252. var tempcanvas = document.createElement("canvas");
  15253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15254. return gl != null && !!window.WebGLRenderingContext;
  15255. }
  15256. catch (e) {
  15257. return false;
  15258. }
  15259. };
  15260. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15261. Engine.ExceptionList = [
  15262. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15263. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15264. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15265. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15266. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15267. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15268. ];
  15269. Engine.Instances = new Array();
  15270. // Const statics
  15271. Engine._ALPHA_DISABLE = 0;
  15272. Engine._ALPHA_ADD = 1;
  15273. Engine._ALPHA_COMBINE = 2;
  15274. Engine._ALPHA_SUBTRACT = 3;
  15275. Engine._ALPHA_MULTIPLY = 4;
  15276. Engine._ALPHA_MAXIMIZED = 5;
  15277. Engine._ALPHA_ONEONE = 6;
  15278. Engine._ALPHA_PREMULTIPLIED = 7;
  15279. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15280. Engine._ALPHA_INTERPOLATE = 9;
  15281. Engine._ALPHA_SCREENMODE = 10;
  15282. Engine._DELAYLOADSTATE_NONE = 0;
  15283. Engine._DELAYLOADSTATE_LOADED = 1;
  15284. Engine._DELAYLOADSTATE_LOADING = 2;
  15285. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15286. Engine._TEXTUREFORMAT_ALPHA = 0;
  15287. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15288. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15289. Engine._TEXTUREFORMAT_RGB = 4;
  15290. Engine._TEXTUREFORMAT_RGBA = 5;
  15291. Engine._TEXTUREFORMAT_R32F = 6;
  15292. Engine._TEXTUREFORMAT_RG32F = 7;
  15293. Engine._TEXTUREFORMAT_RGB32F = 8;
  15294. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15295. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15296. Engine._TEXTURETYPE_FLOAT = 1;
  15297. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15298. // Depht or Stencil test Constants.
  15299. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15300. 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.
  15301. 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.
  15302. 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.
  15303. 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.
  15304. 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.
  15305. 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.
  15306. 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.
  15307. // Stencil Actions Constants.
  15308. Engine._KEEP = 0x1E00;
  15309. Engine._REPLACE = 0x1E01;
  15310. Engine._INCR = 0x1E02;
  15311. Engine._DECR = 0x1E03;
  15312. Engine._INVERT = 0x150A;
  15313. Engine._INCR_WRAP = 0x8507;
  15314. Engine._DECR_WRAP = 0x8508;
  15315. // Texture rescaling mode
  15316. Engine._SCALEMODE_FLOOR = 1;
  15317. Engine._SCALEMODE_NEAREST = 2;
  15318. Engine._SCALEMODE_CEILING = 3;
  15319. // Updatable statics so stick with vars here
  15320. Engine.CollisionsEpsilon = 0.001;
  15321. Engine.CodeRepository = "src/";
  15322. Engine.ShadersRepository = "src/Shaders/";
  15323. return Engine;
  15324. }());
  15325. BABYLON.Engine = Engine;
  15326. })(BABYLON || (BABYLON = {}));
  15327. //# sourceMappingURL=babylon.engine.js.map
  15328. var BABYLON;
  15329. (function (BABYLON) {
  15330. /**
  15331. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15332. */
  15333. var Node = /** @class */ (function () {
  15334. /**
  15335. * Creates a new Node
  15336. * @param {string} name - the name and id to be given to this node
  15337. * @param {BABYLON.Scene} the scene this node will be added to
  15338. */
  15339. function Node(name, scene) {
  15340. if (scene === void 0) { scene = null; }
  15341. /**
  15342. * Gets or sets a string used to store user defined state for the node
  15343. */
  15344. this.state = "";
  15345. /**
  15346. * Gets or sets an object used to store user defined information for the node
  15347. */
  15348. this.metadata = null;
  15349. /**
  15350. * Gets or sets a boolean used to define if the node must be serialized
  15351. */
  15352. this.doNotSerialize = false;
  15353. /** @ignore */
  15354. this._isDisposed = false;
  15355. /**
  15356. * Gets a list of {BABYLON.Animation} associated with the node
  15357. */
  15358. this.animations = new Array();
  15359. this._ranges = {};
  15360. this._isEnabled = true;
  15361. this._isReady = true;
  15362. /** @ignore */
  15363. this._currentRenderId = -1;
  15364. this._parentRenderId = -1;
  15365. /**
  15366. * An event triggered when the mesh is disposed
  15367. * @type {BABYLON.Observable}
  15368. */
  15369. this.onDisposeObservable = new BABYLON.Observable();
  15370. // Behaviors
  15371. this._behaviors = new Array();
  15372. this.name = name;
  15373. this.id = name;
  15374. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15375. this.uniqueId = this._scene.getUniqueId();
  15376. this._initCache();
  15377. }
  15378. /**
  15379. * Gets a boolean indicating if the node has been disposed
  15380. * @returns true if the node was disposed
  15381. */
  15382. Node.prototype.isDisposed = function () {
  15383. return this._isDisposed;
  15384. };
  15385. Object.defineProperty(Node.prototype, "parent", {
  15386. get: function () {
  15387. return this._parentNode;
  15388. },
  15389. /**
  15390. * Gets or sets the parent of the node
  15391. */
  15392. set: function (parent) {
  15393. if (this._parentNode === parent) {
  15394. return;
  15395. }
  15396. // Remove self from list of children of parent
  15397. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15398. var index = this._parentNode._children.indexOf(this);
  15399. if (index !== -1) {
  15400. this._parentNode._children.splice(index, 1);
  15401. }
  15402. }
  15403. // Store new parent
  15404. this._parentNode = parent;
  15405. // Add as child to new parent
  15406. if (this._parentNode) {
  15407. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15408. this._parentNode._children = new Array();
  15409. }
  15410. this._parentNode._children.push(this);
  15411. }
  15412. },
  15413. enumerable: true,
  15414. configurable: true
  15415. });
  15416. /**
  15417. * Gets a string idenfifying the name of the class
  15418. * @returns "Node" string
  15419. */
  15420. Node.prototype.getClassName = function () {
  15421. return "Node";
  15422. };
  15423. Object.defineProperty(Node.prototype, "onDispose", {
  15424. /**
  15425. * Sets a callback that will be raised when the node will be disposed
  15426. */
  15427. set: function (callback) {
  15428. if (this._onDisposeObserver) {
  15429. this.onDisposeObservable.remove(this._onDisposeObserver);
  15430. }
  15431. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15432. },
  15433. enumerable: true,
  15434. configurable: true
  15435. });
  15436. /**
  15437. * Gets the scene of the node
  15438. * @returns a {BABYLON.Scene}
  15439. */
  15440. Node.prototype.getScene = function () {
  15441. return this._scene;
  15442. };
  15443. /**
  15444. * Gets the engine of the node
  15445. * @returns a {BABYLON.Engine}
  15446. */
  15447. Node.prototype.getEngine = function () {
  15448. return this._scene.getEngine();
  15449. };
  15450. /**
  15451. * Attach a behavior to the node
  15452. * @see http://doc.babylonjs.com/features/behaviour
  15453. * @param behavior defines the behavior to attach
  15454. * @returns the current Node
  15455. */
  15456. Node.prototype.addBehavior = function (behavior) {
  15457. var _this = this;
  15458. var index = this._behaviors.indexOf(behavior);
  15459. if (index !== -1) {
  15460. return this;
  15461. }
  15462. behavior.init();
  15463. if (this._scene.isLoading) {
  15464. // We defer the attach when the scene will be loaded
  15465. var observer = this._scene.onDataLoadedObservable.add(function () {
  15466. behavior.attach(_this);
  15467. setTimeout(function () {
  15468. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15469. _this._scene.onDataLoadedObservable.remove(observer);
  15470. }, 0);
  15471. });
  15472. }
  15473. else {
  15474. behavior.attach(this);
  15475. }
  15476. this._behaviors.push(behavior);
  15477. return this;
  15478. };
  15479. /**
  15480. * Remove an attached behavior
  15481. * @see http://doc.babylonjs.com/features/behaviour
  15482. * @param behavior defines the behavior to attach
  15483. * @returns the current Node
  15484. */
  15485. Node.prototype.removeBehavior = function (behavior) {
  15486. var index = this._behaviors.indexOf(behavior);
  15487. if (index === -1) {
  15488. return this;
  15489. }
  15490. this._behaviors[index].detach();
  15491. this._behaviors.splice(index, 1);
  15492. return this;
  15493. };
  15494. Object.defineProperty(Node.prototype, "behaviors", {
  15495. /**
  15496. * Gets the list of attached behaviors
  15497. * @see http://doc.babylonjs.com/features/behaviour
  15498. */
  15499. get: function () {
  15500. return this._behaviors;
  15501. },
  15502. enumerable: true,
  15503. configurable: true
  15504. });
  15505. /**
  15506. * Gets an attached behavior by name
  15507. * @param name defines the name of the behavior to look for
  15508. * @see http://doc.babylonjs.com/features/behaviour
  15509. * @returns null if behavior was not found else the requested behavior
  15510. */
  15511. Node.prototype.getBehaviorByName = function (name) {
  15512. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15513. var behavior = _a[_i];
  15514. if (behavior.name === name) {
  15515. return behavior;
  15516. }
  15517. }
  15518. return null;
  15519. };
  15520. /**
  15521. * Returns the world matrix of the node
  15522. * @returns a matrix containing the node's world matrix
  15523. */
  15524. Node.prototype.getWorldMatrix = function () {
  15525. return BABYLON.Matrix.Identity();
  15526. };
  15527. // override it in derived class if you add new variables to the cache
  15528. // and call the parent class method
  15529. /** @ignore */
  15530. Node.prototype._initCache = function () {
  15531. this._cache = {};
  15532. this._cache.parent = undefined;
  15533. };
  15534. /** @ignore */
  15535. Node.prototype.updateCache = function (force) {
  15536. if (!force && this.isSynchronized())
  15537. return;
  15538. this._cache.parent = this.parent;
  15539. this._updateCache();
  15540. };
  15541. // override it in derived class if you add new variables to the cache
  15542. // and call the parent class method if !ignoreParentClass
  15543. /** @ignore */
  15544. Node.prototype._updateCache = function (ignoreParentClass) {
  15545. };
  15546. // override it in derived class if you add new variables to the cache
  15547. /** @ignore */
  15548. Node.prototype._isSynchronized = function () {
  15549. return true;
  15550. };
  15551. /** @ignore */
  15552. Node.prototype._markSyncedWithParent = function () {
  15553. if (this.parent) {
  15554. this._parentRenderId = this.parent._currentRenderId;
  15555. }
  15556. };
  15557. /** @ignore */
  15558. Node.prototype.isSynchronizedWithParent = function () {
  15559. if (!this.parent) {
  15560. return true;
  15561. }
  15562. if (this._parentRenderId !== this.parent._currentRenderId) {
  15563. return false;
  15564. }
  15565. return this.parent.isSynchronized();
  15566. };
  15567. /** @ignore */
  15568. Node.prototype.isSynchronized = function (updateCache) {
  15569. var check = this.hasNewParent();
  15570. check = check || !this.isSynchronizedWithParent();
  15571. check = check || !this._isSynchronized();
  15572. if (updateCache)
  15573. this.updateCache(true);
  15574. return !check;
  15575. };
  15576. /** @ignore */
  15577. Node.prototype.hasNewParent = function (update) {
  15578. if (this._cache.parent === this.parent)
  15579. return false;
  15580. if (update)
  15581. this._cache.parent = this.parent;
  15582. return true;
  15583. };
  15584. /**
  15585. * Is this node ready to be used/rendered
  15586. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15587. * @return true if the node is ready
  15588. */
  15589. Node.prototype.isReady = function (completeCheck) {
  15590. if (completeCheck === void 0) { completeCheck = false; }
  15591. return this._isReady;
  15592. };
  15593. /**
  15594. * Is this node enabled?
  15595. * 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
  15596. * @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
  15597. * @return whether this node (and its parent) is enabled
  15598. * @see setEnabled
  15599. */
  15600. Node.prototype.isEnabled = function (checkAncestors) {
  15601. if (checkAncestors === void 0) { checkAncestors = true; }
  15602. if (checkAncestors === false) {
  15603. return this._isEnabled;
  15604. }
  15605. if (this._isEnabled === false) {
  15606. return false;
  15607. }
  15608. if (this.parent !== undefined && this.parent !== null) {
  15609. return this.parent.isEnabled(checkAncestors);
  15610. }
  15611. return true;
  15612. };
  15613. /**
  15614. * Set the enabled state of this node
  15615. * @param value defines the new enabled state
  15616. * @see isEnabled
  15617. */
  15618. Node.prototype.setEnabled = function (value) {
  15619. this._isEnabled = value;
  15620. };
  15621. /**
  15622. * Is this node a descendant of the given node?
  15623. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15624. * @param ancestor defines the parent node to inspect
  15625. * @see parent
  15626. * @returns a boolean indicating if this node is a descendant of the given node
  15627. */
  15628. Node.prototype.isDescendantOf = function (ancestor) {
  15629. if (this.parent) {
  15630. if (this.parent === ancestor) {
  15631. return true;
  15632. }
  15633. return this.parent.isDescendantOf(ancestor);
  15634. }
  15635. return false;
  15636. };
  15637. /** @ignore */
  15638. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15639. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15640. if (!this._children) {
  15641. return;
  15642. }
  15643. for (var index = 0; index < this._children.length; index++) {
  15644. var item = this._children[index];
  15645. if (!predicate || predicate(item)) {
  15646. results.push(item);
  15647. }
  15648. if (!directDescendantsOnly) {
  15649. item._getDescendants(results, false, predicate);
  15650. }
  15651. }
  15652. };
  15653. /**
  15654. * Will return all nodes that have this node as ascendant
  15655. * @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
  15656. * @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
  15657. * @return all children nodes of all types
  15658. */
  15659. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15660. var results = new Array();
  15661. this._getDescendants(results, directDescendantsOnly, predicate);
  15662. return results;
  15663. };
  15664. /**
  15665. * Get all child-meshes of this node
  15666. * @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
  15667. * @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
  15668. * @returns an array of {BABYLON.AbstractMesh}
  15669. */
  15670. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15671. var results = [];
  15672. this._getDescendants(results, directDescendantsOnly, function (node) {
  15673. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15674. });
  15675. return results;
  15676. };
  15677. /**
  15678. * Get all child-transformNodes of this node
  15679. * @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
  15680. * @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
  15681. * @returns an array of {BABYLON.TransformNode}
  15682. */
  15683. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15684. var results = [];
  15685. this._getDescendants(results, directDescendantsOnly, function (node) {
  15686. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15687. });
  15688. return results;
  15689. };
  15690. /**
  15691. * Get all direct children of this node
  15692. * @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
  15693. * @returns an array of {BABYLON.Node}
  15694. */
  15695. Node.prototype.getChildren = function (predicate) {
  15696. return this.getDescendants(true, predicate);
  15697. };
  15698. /** @ignore */
  15699. Node.prototype._setReady = function (state) {
  15700. if (state === this._isReady) {
  15701. return;
  15702. }
  15703. if (!state) {
  15704. this._isReady = false;
  15705. return;
  15706. }
  15707. this._isReady = true;
  15708. if (this.onReady) {
  15709. this.onReady(this);
  15710. }
  15711. };
  15712. /**
  15713. * Get an animation by name
  15714. * @param name defines the name of the animation to look for
  15715. * @returns null if not found else the requested animation
  15716. */
  15717. Node.prototype.getAnimationByName = function (name) {
  15718. for (var i = 0; i < this.animations.length; i++) {
  15719. var animation = this.animations[i];
  15720. if (animation.name === name) {
  15721. return animation;
  15722. }
  15723. }
  15724. return null;
  15725. };
  15726. /**
  15727. * Creates an animation range for this node
  15728. * @param name defines the name of the range
  15729. * @param from defines the starting key
  15730. * @param to defines the end key
  15731. */
  15732. Node.prototype.createAnimationRange = function (name, from, to) {
  15733. // check name not already in use
  15734. if (!this._ranges[name]) {
  15735. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15736. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15737. if (this.animations[i]) {
  15738. this.animations[i].createRange(name, from, to);
  15739. }
  15740. }
  15741. }
  15742. };
  15743. /**
  15744. * Delete a specific animation range
  15745. * @param name defines the name of the range to delete
  15746. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15747. */
  15748. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15749. if (deleteFrames === void 0) { deleteFrames = true; }
  15750. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15751. if (this.animations[i]) {
  15752. this.animations[i].deleteRange(name, deleteFrames);
  15753. }
  15754. }
  15755. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15756. };
  15757. /**
  15758. * Get an animation range by name
  15759. * @param name defines the name of the animation range to look for
  15760. * @returns null if not found else the requested animation range
  15761. */
  15762. Node.prototype.getAnimationRange = function (name) {
  15763. return this._ranges[name];
  15764. };
  15765. /**
  15766. * Will start the animation sequence
  15767. * @param name defines the range frames for animation sequence
  15768. * @param loop defines if the animation should loop (false by default)
  15769. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15770. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15771. * @returns the object created for this animation. If range does not exist, it will return null
  15772. */
  15773. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15774. var range = this.getAnimationRange(name);
  15775. if (!range) {
  15776. return null;
  15777. }
  15778. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15779. };
  15780. /**
  15781. * Serialize animation ranges into a JSON compatible object
  15782. * @returns serialization object
  15783. */
  15784. Node.prototype.serializeAnimationRanges = function () {
  15785. var serializationRanges = [];
  15786. for (var name in this._ranges) {
  15787. var localRange = this._ranges[name];
  15788. if (!localRange) {
  15789. continue;
  15790. }
  15791. var range = {};
  15792. range.name = name;
  15793. range.from = localRange.from;
  15794. range.to = localRange.to;
  15795. serializationRanges.push(range);
  15796. }
  15797. return serializationRanges;
  15798. };
  15799. /**
  15800. * Computes the world matrix of the node
  15801. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15802. * @returns the world matrix
  15803. */
  15804. Node.prototype.computeWorldMatrix = function (force) {
  15805. return BABYLON.Matrix.Identity();
  15806. };
  15807. /**
  15808. * Releases all associated resources
  15809. */
  15810. Node.prototype.dispose = function () {
  15811. this.parent = null;
  15812. // Callback
  15813. this.onDisposeObservable.notifyObservers(this);
  15814. this.onDisposeObservable.clear();
  15815. // Behaviors
  15816. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15817. var behavior = _a[_i];
  15818. behavior.detach();
  15819. }
  15820. this._behaviors = [];
  15821. this._isDisposed = true;
  15822. };
  15823. /**
  15824. * Parse animation range data from a serialization object and store them into a given node
  15825. * @param node defines where to store the animation ranges
  15826. * @param parsedNode defines the serialization object to read data from
  15827. * @param scene defines the hosting scene
  15828. */
  15829. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15830. if (parsedNode.ranges) {
  15831. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15832. var data = parsedNode.ranges[index];
  15833. node.createAnimationRange(data.name, data.from, data.to);
  15834. }
  15835. }
  15836. };
  15837. __decorate([
  15838. BABYLON.serialize()
  15839. ], Node.prototype, "name", void 0);
  15840. __decorate([
  15841. BABYLON.serialize()
  15842. ], Node.prototype, "id", void 0);
  15843. __decorate([
  15844. BABYLON.serialize()
  15845. ], Node.prototype, "uniqueId", void 0);
  15846. __decorate([
  15847. BABYLON.serialize()
  15848. ], Node.prototype, "state", void 0);
  15849. __decorate([
  15850. BABYLON.serialize()
  15851. ], Node.prototype, "metadata", void 0);
  15852. return Node;
  15853. }());
  15854. BABYLON.Node = Node;
  15855. })(BABYLON || (BABYLON = {}));
  15856. //# sourceMappingURL=babylon.node.js.map
  15857. var BABYLON;
  15858. (function (BABYLON) {
  15859. var BoundingSphere = /** @class */ (function () {
  15860. function BoundingSphere(minimum, maximum) {
  15861. this.minimum = minimum;
  15862. this.maximum = maximum;
  15863. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15864. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15865. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15866. this.radius = distance * 0.5;
  15867. this.centerWorld = BABYLON.Vector3.Zero();
  15868. this._update(BABYLON.Matrix.Identity());
  15869. }
  15870. // Methods
  15871. BoundingSphere.prototype._update = function (world) {
  15872. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15873. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15874. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15875. };
  15876. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15877. for (var i = 0; i < 6; i++) {
  15878. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15879. return false;
  15880. }
  15881. return true;
  15882. };
  15883. BoundingSphere.prototype.intersectsPoint = function (point) {
  15884. var x = this.centerWorld.x - point.x;
  15885. var y = this.centerWorld.y - point.y;
  15886. var z = this.centerWorld.z - point.z;
  15887. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15888. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15889. return false;
  15890. return true;
  15891. };
  15892. // Statics
  15893. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15894. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15895. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15896. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15897. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15898. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15899. return false;
  15900. return true;
  15901. };
  15902. return BoundingSphere;
  15903. }());
  15904. BABYLON.BoundingSphere = BoundingSphere;
  15905. })(BABYLON || (BABYLON = {}));
  15906. //# sourceMappingURL=babylon.boundingSphere.js.map
  15907. var BABYLON;
  15908. (function (BABYLON) {
  15909. var BoundingBox = /** @class */ (function () {
  15910. function BoundingBox(minimum, maximum) {
  15911. this.minimum = minimum;
  15912. this.maximum = maximum;
  15913. this.vectors = new Array();
  15914. this.vectorsWorld = new Array();
  15915. // Bounding vectors
  15916. this.vectors.push(this.minimum.clone());
  15917. this.vectors.push(this.maximum.clone());
  15918. this.vectors.push(this.minimum.clone());
  15919. this.vectors[2].x = this.maximum.x;
  15920. this.vectors.push(this.minimum.clone());
  15921. this.vectors[3].y = this.maximum.y;
  15922. this.vectors.push(this.minimum.clone());
  15923. this.vectors[4].z = this.maximum.z;
  15924. this.vectors.push(this.maximum.clone());
  15925. this.vectors[5].z = this.minimum.z;
  15926. this.vectors.push(this.maximum.clone());
  15927. this.vectors[6].x = this.minimum.x;
  15928. this.vectors.push(this.maximum.clone());
  15929. this.vectors[7].y = this.minimum.y;
  15930. // OBB
  15931. this.center = this.maximum.add(this.minimum).scale(0.5);
  15932. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15933. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15934. // World
  15935. for (var index = 0; index < this.vectors.length; index++) {
  15936. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15937. }
  15938. this.minimumWorld = BABYLON.Vector3.Zero();
  15939. this.maximumWorld = BABYLON.Vector3.Zero();
  15940. this.centerWorld = BABYLON.Vector3.Zero();
  15941. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15942. this._update(BABYLON.Matrix.Identity());
  15943. }
  15944. // Methods
  15945. BoundingBox.prototype.getWorldMatrix = function () {
  15946. return this._worldMatrix;
  15947. };
  15948. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15949. this._worldMatrix.copyFrom(matrix);
  15950. return this;
  15951. };
  15952. BoundingBox.prototype._update = function (world) {
  15953. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15954. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15955. for (var index = 0; index < this.vectors.length; index++) {
  15956. var v = this.vectorsWorld[index];
  15957. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15958. if (v.x < this.minimumWorld.x)
  15959. this.minimumWorld.x = v.x;
  15960. if (v.y < this.minimumWorld.y)
  15961. this.minimumWorld.y = v.y;
  15962. if (v.z < this.minimumWorld.z)
  15963. this.minimumWorld.z = v.z;
  15964. if (v.x > this.maximumWorld.x)
  15965. this.maximumWorld.x = v.x;
  15966. if (v.y > this.maximumWorld.y)
  15967. this.maximumWorld.y = v.y;
  15968. if (v.z > this.maximumWorld.z)
  15969. this.maximumWorld.z = v.z;
  15970. }
  15971. // Extend
  15972. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15973. this.extendSizeWorld.scaleInPlace(0.5);
  15974. // OBB
  15975. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15976. this.centerWorld.scaleInPlace(0.5);
  15977. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15978. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15979. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15980. this._worldMatrix = world;
  15981. };
  15982. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15983. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15984. };
  15985. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15986. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15987. };
  15988. BoundingBox.prototype.intersectsPoint = function (point) {
  15989. var delta = -BABYLON.Epsilon;
  15990. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15991. return false;
  15992. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15993. return false;
  15994. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15995. return false;
  15996. return true;
  15997. };
  15998. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15999. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16000. };
  16001. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16002. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16003. return false;
  16004. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16005. return false;
  16006. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16007. return false;
  16008. return true;
  16009. };
  16010. // Statics
  16011. BoundingBox.Intersects = function (box0, box1) {
  16012. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16013. return false;
  16014. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16015. return false;
  16016. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16017. return false;
  16018. return true;
  16019. };
  16020. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16021. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16022. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16023. return (num <= (sphereRadius * sphereRadius));
  16024. };
  16025. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16026. for (var p = 0; p < 6; p++) {
  16027. for (var i = 0; i < 8; i++) {
  16028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16029. return false;
  16030. }
  16031. }
  16032. }
  16033. return true;
  16034. };
  16035. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16036. for (var p = 0; p < 6; p++) {
  16037. var inCount = 8;
  16038. for (var i = 0; i < 8; i++) {
  16039. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16040. --inCount;
  16041. }
  16042. else {
  16043. break;
  16044. }
  16045. }
  16046. if (inCount === 0)
  16047. return false;
  16048. }
  16049. return true;
  16050. };
  16051. return BoundingBox;
  16052. }());
  16053. BABYLON.BoundingBox = BoundingBox;
  16054. })(BABYLON || (BABYLON = {}));
  16055. //# sourceMappingURL=babylon.boundingBox.js.map
  16056. var BABYLON;
  16057. (function (BABYLON) {
  16058. var computeBoxExtents = function (axis, box) {
  16059. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16060. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16061. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16062. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16063. var r = r0 + r1 + r2;
  16064. return {
  16065. min: p - r,
  16066. max: p + r
  16067. };
  16068. };
  16069. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16070. var axisOverlap = function (axis, box0, box1) {
  16071. var result0 = computeBoxExtents(axis, box0);
  16072. var result1 = computeBoxExtents(axis, box1);
  16073. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16074. };
  16075. var BoundingInfo = /** @class */ (function () {
  16076. function BoundingInfo(minimum, maximum) {
  16077. this.minimum = minimum;
  16078. this.maximum = maximum;
  16079. this._isLocked = false;
  16080. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16081. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16082. }
  16083. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16084. get: function () {
  16085. return this._isLocked;
  16086. },
  16087. set: function (value) {
  16088. this._isLocked = value;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. // Methods
  16094. BoundingInfo.prototype.update = function (world) {
  16095. if (this._isLocked) {
  16096. return;
  16097. }
  16098. this.boundingBox._update(world);
  16099. this.boundingSphere._update(world);
  16100. };
  16101. /**
  16102. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16103. * @param center New center of the bounding info
  16104. * @param extend New extend of the bounding info
  16105. */
  16106. BoundingInfo.prototype.centerOn = function (center, extend) {
  16107. this.minimum = center.subtract(extend);
  16108. this.maximum = center.add(extend);
  16109. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16110. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16111. return this;
  16112. };
  16113. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16114. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16115. return false;
  16116. return this.boundingBox.isInFrustum(frustumPlanes);
  16117. };
  16118. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16119. /**
  16120. * Gets the world distance between the min and max points of the bounding box
  16121. */
  16122. get: function () {
  16123. var boundingBox = this.boundingBox;
  16124. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16125. return size.length();
  16126. },
  16127. enumerable: true,
  16128. configurable: true
  16129. });
  16130. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16131. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16132. };
  16133. BoundingInfo.prototype._checkCollision = function (collider) {
  16134. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16135. };
  16136. BoundingInfo.prototype.intersectsPoint = function (point) {
  16137. if (!this.boundingSphere.centerWorld) {
  16138. return false;
  16139. }
  16140. if (!this.boundingSphere.intersectsPoint(point)) {
  16141. return false;
  16142. }
  16143. if (!this.boundingBox.intersectsPoint(point)) {
  16144. return false;
  16145. }
  16146. return true;
  16147. };
  16148. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16149. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16150. return false;
  16151. }
  16152. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16153. return false;
  16154. }
  16155. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16156. return false;
  16157. }
  16158. if (!precise) {
  16159. return true;
  16160. }
  16161. var box0 = this.boundingBox;
  16162. var box1 = boundingInfo.boundingBox;
  16163. if (!axisOverlap(box0.directions[0], box0, box1))
  16164. return false;
  16165. if (!axisOverlap(box0.directions[1], box0, box1))
  16166. return false;
  16167. if (!axisOverlap(box0.directions[2], box0, box1))
  16168. return false;
  16169. if (!axisOverlap(box1.directions[0], box0, box1))
  16170. return false;
  16171. if (!axisOverlap(box1.directions[1], box0, box1))
  16172. return false;
  16173. if (!axisOverlap(box1.directions[2], box0, box1))
  16174. return false;
  16175. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16176. return false;
  16177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16178. return false;
  16179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16180. return false;
  16181. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16182. return false;
  16183. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16184. return false;
  16185. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16186. return false;
  16187. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16188. return false;
  16189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16190. return false;
  16191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16192. return false;
  16193. return true;
  16194. };
  16195. return BoundingInfo;
  16196. }());
  16197. BABYLON.BoundingInfo = BoundingInfo;
  16198. })(BABYLON || (BABYLON = {}));
  16199. //# sourceMappingURL=babylon.boundingInfo.js.map
  16200. var BABYLON;
  16201. (function (BABYLON) {
  16202. var TransformNode = /** @class */ (function (_super) {
  16203. __extends(TransformNode, _super);
  16204. function TransformNode(name, scene, isPure) {
  16205. if (scene === void 0) { scene = null; }
  16206. if (isPure === void 0) { isPure = true; }
  16207. var _this = _super.call(this, name, scene) || this;
  16208. // Properties
  16209. _this._rotation = BABYLON.Vector3.Zero();
  16210. _this._scaling = BABYLON.Vector3.One();
  16211. _this._isDirty = false;
  16212. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16213. _this.scalingDeterminant = 1;
  16214. _this.infiniteDistance = false;
  16215. _this.position = BABYLON.Vector3.Zero();
  16216. _this._localWorld = BABYLON.Matrix.Zero();
  16217. _this._worldMatrix = BABYLON.Matrix.Zero();
  16218. _this._worldMatrixDeterminant = 0;
  16219. _this._absolutePosition = BABYLON.Vector3.Zero();
  16220. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16221. _this._postMultiplyPivotMatrix = false;
  16222. _this._isWorldMatrixFrozen = false;
  16223. /**
  16224. * An event triggered after the world matrix is updated
  16225. * @type {BABYLON.Observable}
  16226. */
  16227. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16228. _this._nonUniformScaling = false;
  16229. if (isPure) {
  16230. _this.getScene().addTransformNode(_this);
  16231. }
  16232. return _this;
  16233. }
  16234. Object.defineProperty(TransformNode.prototype, "rotation", {
  16235. /**
  16236. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16237. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16238. * Default : (0.0, 0.0, 0.0)
  16239. */
  16240. get: function () {
  16241. return this._rotation;
  16242. },
  16243. set: function (newRotation) {
  16244. this._rotation = newRotation;
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(TransformNode.prototype, "scaling", {
  16250. /**
  16251. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16252. * Default : (1.0, 1.0, 1.0)
  16253. */
  16254. get: function () {
  16255. return this._scaling;
  16256. },
  16257. /**
  16258. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16259. * Default : (1.0, 1.0, 1.0)
  16260. */
  16261. set: function (newScaling) {
  16262. this._scaling = newScaling;
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16268. /**
  16269. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16270. * It's null by default.
  16271. * 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)
  16272. */
  16273. get: function () {
  16274. return this._rotationQuaternion;
  16275. },
  16276. set: function (quaternion) {
  16277. this._rotationQuaternion = quaternion;
  16278. //reset the rotation vector.
  16279. if (quaternion && this.rotation.length()) {
  16280. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16281. }
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. /**
  16287. * Returns the latest update of the World matrix
  16288. * Returns a Matrix.
  16289. */
  16290. TransformNode.prototype.getWorldMatrix = function () {
  16291. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16292. this.computeWorldMatrix();
  16293. }
  16294. return this._worldMatrix;
  16295. };
  16296. /**
  16297. * Returns the latest update of the World matrix determinant.
  16298. */
  16299. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16300. return this._worldMatrixDeterminant;
  16301. };
  16302. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16303. /**
  16304. * Returns directly the latest state of the mesh World matrix.
  16305. * A Matrix is returned.
  16306. */
  16307. get: function () {
  16308. return this._worldMatrix;
  16309. },
  16310. enumerable: true,
  16311. configurable: true
  16312. });
  16313. /**
  16314. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16315. * Returns the AbstractMesh.
  16316. */
  16317. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16318. this._poseMatrix.copyFrom(matrix);
  16319. return this;
  16320. };
  16321. /**
  16322. * Returns the mesh Pose matrix.
  16323. * Returned object : Matrix
  16324. */
  16325. TransformNode.prototype.getPoseMatrix = function () {
  16326. return this._poseMatrix;
  16327. };
  16328. TransformNode.prototype._isSynchronized = function () {
  16329. if (this._isDirty) {
  16330. return false;
  16331. }
  16332. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16333. return false;
  16334. if (this._cache.pivotMatrixUpdated) {
  16335. return false;
  16336. }
  16337. if (this.infiniteDistance) {
  16338. return false;
  16339. }
  16340. if (!this._cache.position.equals(this.position))
  16341. return false;
  16342. if (this.rotationQuaternion) {
  16343. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16344. return false;
  16345. }
  16346. if (!this._cache.rotation.equals(this.rotation))
  16347. return false;
  16348. if (!this._cache.scaling.equals(this.scaling))
  16349. return false;
  16350. return true;
  16351. };
  16352. TransformNode.prototype._initCache = function () {
  16353. _super.prototype._initCache.call(this);
  16354. this._cache.localMatrixUpdated = false;
  16355. this._cache.position = BABYLON.Vector3.Zero();
  16356. this._cache.scaling = BABYLON.Vector3.Zero();
  16357. this._cache.rotation = BABYLON.Vector3.Zero();
  16358. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16359. this._cache.billboardMode = -1;
  16360. };
  16361. TransformNode.prototype.markAsDirty = function (property) {
  16362. if (property === "rotation") {
  16363. this.rotationQuaternion = null;
  16364. }
  16365. this._currentRenderId = Number.MAX_VALUE;
  16366. this._isDirty = true;
  16367. return this;
  16368. };
  16369. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16370. /**
  16371. * Returns the current mesh absolute position.
  16372. * Retuns a Vector3.
  16373. */
  16374. get: function () {
  16375. return this._absolutePosition;
  16376. },
  16377. enumerable: true,
  16378. configurable: true
  16379. });
  16380. /**
  16381. * Sets a new matrix to apply before all other transformation
  16382. * @param matrix defines the transform matrix
  16383. * @returns the current TransformNode
  16384. */
  16385. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16386. return this.setPivotMatrix(matrix, false);
  16387. };
  16388. /**
  16389. * Sets a new pivot matrix to the current node
  16390. * @param matrix defines the new pivot matrix to use
  16391. * @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
  16392. * @returns the current TransformNode
  16393. */
  16394. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16395. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16396. this._pivotMatrix = matrix.clone();
  16397. this._cache.pivotMatrixUpdated = true;
  16398. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16399. if (this._postMultiplyPivotMatrix) {
  16400. if (!this._pivotMatrixInverse) {
  16401. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16402. }
  16403. else {
  16404. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16405. }
  16406. }
  16407. return this;
  16408. };
  16409. /**
  16410. * Returns the mesh pivot matrix.
  16411. * Default : Identity.
  16412. * A Matrix is returned.
  16413. */
  16414. TransformNode.prototype.getPivotMatrix = function () {
  16415. return this._pivotMatrix;
  16416. };
  16417. /**
  16418. * Prevents the World matrix to be computed any longer.
  16419. * Returns the AbstractMesh.
  16420. */
  16421. TransformNode.prototype.freezeWorldMatrix = function () {
  16422. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16423. this.computeWorldMatrix(true);
  16424. this._isWorldMatrixFrozen = true;
  16425. return this;
  16426. };
  16427. /**
  16428. * Allows back the World matrix computation.
  16429. * Returns the AbstractMesh.
  16430. */
  16431. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16432. this._isWorldMatrixFrozen = false;
  16433. this.computeWorldMatrix(true);
  16434. return this;
  16435. };
  16436. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16437. /**
  16438. * True if the World matrix has been frozen.
  16439. * Returns a boolean.
  16440. */
  16441. get: function () {
  16442. return this._isWorldMatrixFrozen;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. /**
  16448. * Retuns the mesh absolute position in the World.
  16449. * Returns a Vector3.
  16450. */
  16451. TransformNode.prototype.getAbsolutePosition = function () {
  16452. this.computeWorldMatrix();
  16453. return this._absolutePosition;
  16454. };
  16455. /**
  16456. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16457. * Returns the AbstractMesh.
  16458. */
  16459. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16460. if (!absolutePosition) {
  16461. return this;
  16462. }
  16463. var absolutePositionX;
  16464. var absolutePositionY;
  16465. var absolutePositionZ;
  16466. if (absolutePosition.x === undefined) {
  16467. if (arguments.length < 3) {
  16468. return this;
  16469. }
  16470. absolutePositionX = arguments[0];
  16471. absolutePositionY = arguments[1];
  16472. absolutePositionZ = arguments[2];
  16473. }
  16474. else {
  16475. absolutePositionX = absolutePosition.x;
  16476. absolutePositionY = absolutePosition.y;
  16477. absolutePositionZ = absolutePosition.z;
  16478. }
  16479. if (this.parent) {
  16480. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16481. invertParentWorldMatrix.invert();
  16482. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16483. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16484. }
  16485. else {
  16486. this.position.x = absolutePositionX;
  16487. this.position.y = absolutePositionY;
  16488. this.position.z = absolutePositionZ;
  16489. }
  16490. return this;
  16491. };
  16492. /**
  16493. * Sets the mesh position in its local space.
  16494. * Returns the AbstractMesh.
  16495. */
  16496. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16497. this.computeWorldMatrix();
  16498. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16499. return this;
  16500. };
  16501. /**
  16502. * Returns the mesh position in the local space from the current World matrix values.
  16503. * Returns a new Vector3.
  16504. */
  16505. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16506. this.computeWorldMatrix();
  16507. var invLocalWorldMatrix = this._localWorld.clone();
  16508. invLocalWorldMatrix.invert();
  16509. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16510. };
  16511. /**
  16512. * Translates the mesh along the passed Vector3 in its local space.
  16513. * Returns the AbstractMesh.
  16514. */
  16515. TransformNode.prototype.locallyTranslate = function (vector3) {
  16516. this.computeWorldMatrix(true);
  16517. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16518. return this;
  16519. };
  16520. /**
  16521. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16522. * @param targetPoint the position (must be in same space as current mesh) to look at
  16523. * @param yawCor optional yaw (y-axis) correction in radians
  16524. * @param pitchCor optional pitch (x-axis) correction in radians
  16525. * @param rollCor optional roll (z-axis) correction in radians
  16526. * @param space the choosen space of the target
  16527. * @returns the TransformNode.
  16528. */
  16529. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16530. if (yawCor === void 0) { yawCor = 0; }
  16531. if (pitchCor === void 0) { pitchCor = 0; }
  16532. if (rollCor === void 0) { rollCor = 0; }
  16533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16534. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16535. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16536. targetPoint.subtractToRef(pos, dv);
  16537. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16538. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16539. var pitch = Math.atan2(dv.y, len);
  16540. if (this.rotationQuaternion) {
  16541. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16542. }
  16543. else {
  16544. this.rotation.x = pitch + pitchCor;
  16545. this.rotation.y = yaw + yawCor;
  16546. this.rotation.z = rollCor;
  16547. }
  16548. return this;
  16549. };
  16550. /**
  16551. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16552. * This Vector3 is expressed in the World space.
  16553. */
  16554. TransformNode.prototype.getDirection = function (localAxis) {
  16555. var result = BABYLON.Vector3.Zero();
  16556. this.getDirectionToRef(localAxis, result);
  16557. return result;
  16558. };
  16559. /**
  16560. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16561. * localAxis is expressed in the mesh local space.
  16562. * result is computed in the Wordl space from the mesh World matrix.
  16563. * Returns the AbstractMesh.
  16564. */
  16565. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16566. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16567. return this;
  16568. };
  16569. /**
  16570. * Sets a new pivot point to the current node
  16571. * @param point defines the new pivot point to use
  16572. * @param space defines if the point is in world or local space (local by default)
  16573. * @returns the current TransformNode
  16574. */
  16575. TransformNode.prototype.setPivotPoint = function (point, space) {
  16576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16577. if (this.getScene().getRenderId() == 0) {
  16578. this.computeWorldMatrix(true);
  16579. }
  16580. var wm = this.getWorldMatrix();
  16581. if (space == BABYLON.Space.WORLD) {
  16582. var tmat = BABYLON.Tmp.Matrix[0];
  16583. wm.invertToRef(tmat);
  16584. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16585. }
  16586. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16587. };
  16588. /**
  16589. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16590. */
  16591. TransformNode.prototype.getPivotPoint = function () {
  16592. var point = BABYLON.Vector3.Zero();
  16593. this.getPivotPointToRef(point);
  16594. return point;
  16595. };
  16596. /**
  16597. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16598. * Returns the AbstractMesh.
  16599. */
  16600. TransformNode.prototype.getPivotPointToRef = function (result) {
  16601. result.x = -this._pivotMatrix.m[12];
  16602. result.y = -this._pivotMatrix.m[13];
  16603. result.z = -this._pivotMatrix.m[14];
  16604. return this;
  16605. };
  16606. /**
  16607. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16608. */
  16609. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16610. var point = BABYLON.Vector3.Zero();
  16611. this.getAbsolutePivotPointToRef(point);
  16612. return point;
  16613. };
  16614. /**
  16615. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16616. * Returns the AbstractMesh.
  16617. */
  16618. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16619. result.x = this._pivotMatrix.m[12];
  16620. result.y = this._pivotMatrix.m[13];
  16621. result.z = this._pivotMatrix.m[14];
  16622. this.getPivotPointToRef(result);
  16623. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16624. return this;
  16625. };
  16626. /**
  16627. * Defines the passed node as the parent of the current node.
  16628. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16629. * Returns the TransformNode.
  16630. */
  16631. TransformNode.prototype.setParent = function (node) {
  16632. if (node === null) {
  16633. var rotation = BABYLON.Tmp.Quaternion[0];
  16634. var position = BABYLON.Tmp.Vector3[0];
  16635. var scale = BABYLON.Tmp.Vector3[1];
  16636. if (this.parent && this.parent.computeWorldMatrix) {
  16637. this.parent.computeWorldMatrix(true);
  16638. }
  16639. this.computeWorldMatrix(true);
  16640. this.getWorldMatrix().decompose(scale, rotation, position);
  16641. if (this.rotationQuaternion) {
  16642. this.rotationQuaternion.copyFrom(rotation);
  16643. }
  16644. else {
  16645. rotation.toEulerAnglesToRef(this.rotation);
  16646. }
  16647. this.scaling.x = scale.x;
  16648. this.scaling.y = scale.y;
  16649. this.scaling.z = scale.z;
  16650. this.position.x = position.x;
  16651. this.position.y = position.y;
  16652. this.position.z = position.z;
  16653. }
  16654. else {
  16655. var rotation = BABYLON.Tmp.Quaternion[0];
  16656. var position = BABYLON.Tmp.Vector3[0];
  16657. var scale = BABYLON.Tmp.Vector3[1];
  16658. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16659. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16660. this.computeWorldMatrix(true);
  16661. node.computeWorldMatrix(true);
  16662. node.getWorldMatrix().invertToRef(invParentMatrix);
  16663. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16664. diffMatrix.decompose(scale, rotation, position);
  16665. if (this.rotationQuaternion) {
  16666. this.rotationQuaternion.copyFrom(rotation);
  16667. }
  16668. else {
  16669. rotation.toEulerAnglesToRef(this.rotation);
  16670. }
  16671. this.position.x = position.x;
  16672. this.position.y = position.y;
  16673. this.position.z = position.z;
  16674. this.scaling.x = scale.x;
  16675. this.scaling.y = scale.y;
  16676. this.scaling.z = scale.z;
  16677. }
  16678. this.parent = node;
  16679. return this;
  16680. };
  16681. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16682. get: function () {
  16683. return this._nonUniformScaling;
  16684. },
  16685. enumerable: true,
  16686. configurable: true
  16687. });
  16688. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16689. if (this._nonUniformScaling === value) {
  16690. return false;
  16691. }
  16692. this._nonUniformScaling = true;
  16693. return true;
  16694. };
  16695. /**
  16696. * Attach the current TransformNode to another TransformNode associated with a bone
  16697. * @param bone Bone affecting the TransformNode
  16698. * @param affectedTransformNode TransformNode associated with the bone
  16699. */
  16700. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16701. this._transformToBoneReferal = affectedTransformNode;
  16702. this.parent = bone;
  16703. if (bone.getWorldMatrix().determinant() < 0) {
  16704. this.scalingDeterminant *= -1;
  16705. }
  16706. return this;
  16707. };
  16708. TransformNode.prototype.detachFromBone = function () {
  16709. if (!this.parent) {
  16710. return this;
  16711. }
  16712. if (this.parent.getWorldMatrix().determinant() < 0) {
  16713. this.scalingDeterminant *= -1;
  16714. }
  16715. this._transformToBoneReferal = null;
  16716. this.parent = null;
  16717. return this;
  16718. };
  16719. /**
  16720. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16721. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16722. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16723. * The passed axis is also normalized.
  16724. * Returns the AbstractMesh.
  16725. */
  16726. TransformNode.prototype.rotate = function (axis, amount, space) {
  16727. axis.normalize();
  16728. if (!this.rotationQuaternion) {
  16729. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16730. this.rotation = BABYLON.Vector3.Zero();
  16731. }
  16732. var rotationQuaternion;
  16733. if (!space || space === BABYLON.Space.LOCAL) {
  16734. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16735. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16736. }
  16737. else {
  16738. if (this.parent) {
  16739. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16740. invertParentWorldMatrix.invert();
  16741. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16742. }
  16743. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16744. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16745. }
  16746. return this;
  16747. };
  16748. /**
  16749. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16750. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16751. * The passed axis is also normalized.
  16752. * Returns the AbstractMesh.
  16753. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16754. */
  16755. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16756. axis.normalize();
  16757. if (!this.rotationQuaternion) {
  16758. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16759. this.rotation.copyFromFloats(0, 0, 0);
  16760. }
  16761. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16762. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16763. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16764. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16765. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16766. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16767. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16768. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16769. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16770. return this;
  16771. };
  16772. /**
  16773. * Translates the mesh along the axis vector for the passed distance in the given space.
  16774. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16775. * Returns the AbstractMesh.
  16776. */
  16777. TransformNode.prototype.translate = function (axis, distance, space) {
  16778. var displacementVector = axis.scale(distance);
  16779. if (!space || space === BABYLON.Space.LOCAL) {
  16780. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16781. this.setPositionWithLocalVector(tempV3);
  16782. }
  16783. else {
  16784. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16785. }
  16786. return this;
  16787. };
  16788. /**
  16789. * Adds a rotation step to the mesh current rotation.
  16790. * x, y, z are Euler angles expressed in radians.
  16791. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16792. * This means this rotation is made in the mesh local space only.
  16793. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16794. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16795. * ```javascript
  16796. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16797. * ```
  16798. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16799. * 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.
  16800. * Returns the AbstractMesh.
  16801. */
  16802. TransformNode.prototype.addRotation = function (x, y, z) {
  16803. var rotationQuaternion;
  16804. if (this.rotationQuaternion) {
  16805. rotationQuaternion = this.rotationQuaternion;
  16806. }
  16807. else {
  16808. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16809. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16810. }
  16811. var accumulation = BABYLON.Tmp.Quaternion[0];
  16812. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16813. rotationQuaternion.multiplyInPlace(accumulation);
  16814. if (!this.rotationQuaternion) {
  16815. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16816. }
  16817. return this;
  16818. };
  16819. /**
  16820. * Computes the mesh World matrix and returns it.
  16821. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16822. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16823. * If the parameter `force`is set to `true`, the actual computation is done.
  16824. * Returns the mesh World Matrix.
  16825. */
  16826. TransformNode.prototype.computeWorldMatrix = function (force) {
  16827. if (this._isWorldMatrixFrozen) {
  16828. return this._worldMatrix;
  16829. }
  16830. if (!force && this.isSynchronized(true)) {
  16831. return this._worldMatrix;
  16832. }
  16833. this._cache.position.copyFrom(this.position);
  16834. this._cache.scaling.copyFrom(this.scaling);
  16835. this._cache.pivotMatrixUpdated = false;
  16836. this._cache.billboardMode = this.billboardMode;
  16837. this._currentRenderId = this.getScene().getRenderId();
  16838. this._isDirty = false;
  16839. // Scaling
  16840. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16841. // Rotation
  16842. //rotate, if quaternion is set and rotation was used
  16843. if (this.rotationQuaternion) {
  16844. var len = this.rotation.length();
  16845. if (len) {
  16846. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16847. this.rotation.copyFromFloats(0, 0, 0);
  16848. }
  16849. }
  16850. if (this.rotationQuaternion) {
  16851. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16852. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16853. }
  16854. else {
  16855. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16856. this._cache.rotation.copyFrom(this.rotation);
  16857. }
  16858. // Translation
  16859. var camera = this.getScene().activeCamera;
  16860. if (this.infiniteDistance && !this.parent && camera) {
  16861. var cameraWorldMatrix = camera.getWorldMatrix();
  16862. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16863. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16864. }
  16865. else {
  16866. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16867. }
  16868. // Composing transformations
  16869. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16870. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16871. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16872. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16873. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16874. // Need to decompose each rotation here
  16875. var currentPosition = BABYLON.Tmp.Vector3[3];
  16876. if (this.parent && this.parent.getWorldMatrix) {
  16877. if (this._transformToBoneReferal) {
  16878. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16879. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16880. }
  16881. else {
  16882. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16883. }
  16884. }
  16885. else {
  16886. currentPosition.copyFrom(this.position);
  16887. }
  16888. currentPosition.subtractInPlace(camera.globalPosition);
  16889. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16890. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16891. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16892. }
  16893. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16894. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16895. }
  16896. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16897. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16898. }
  16899. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16900. }
  16901. else {
  16902. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16903. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16904. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16905. }
  16906. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16907. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16908. }
  16909. // Local world
  16910. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16911. // Parent
  16912. if (this.parent && this.parent.getWorldMatrix) {
  16913. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16914. if (this._transformToBoneReferal) {
  16915. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16916. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16917. }
  16918. else {
  16919. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16920. }
  16921. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16922. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16923. this._worldMatrix.copyFrom(this._localWorld);
  16924. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16925. }
  16926. else {
  16927. if (this._transformToBoneReferal) {
  16928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16929. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16930. }
  16931. else {
  16932. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16933. }
  16934. }
  16935. this._markSyncedWithParent();
  16936. }
  16937. else {
  16938. this._worldMatrix.copyFrom(this._localWorld);
  16939. }
  16940. // Post multiply inverse of pivotMatrix
  16941. if (this._postMultiplyPivotMatrix) {
  16942. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16943. }
  16944. // Normal matrix
  16945. if (this.scaling.isNonUniform) {
  16946. this._updateNonUniformScalingState(true);
  16947. }
  16948. else if (this.parent && this.parent._nonUniformScaling) {
  16949. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16950. }
  16951. else {
  16952. this._updateNonUniformScalingState(false);
  16953. }
  16954. this._afterComputeWorldMatrix();
  16955. // Absolute position
  16956. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16957. // Callbacks
  16958. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16959. if (!this._poseMatrix) {
  16960. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16961. }
  16962. // Cache the determinant
  16963. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16964. return this._worldMatrix;
  16965. };
  16966. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16967. };
  16968. /**
  16969. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16970. * @param func: callback function to add
  16971. *
  16972. * Returns the TransformNode.
  16973. */
  16974. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16975. this.onAfterWorldMatrixUpdateObservable.add(func);
  16976. return this;
  16977. };
  16978. /**
  16979. * Removes a registered callback function.
  16980. * Returns the TransformNode.
  16981. */
  16982. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16983. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16984. return this;
  16985. };
  16986. /**
  16987. * Clone the current transform node
  16988. * Returns the new transform node
  16989. * @param name Name of the new clone
  16990. * @param newParent New parent for the clone
  16991. * @param doNotCloneChildren Do not clone children hierarchy
  16992. */
  16993. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16994. var _this = this;
  16995. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16996. result.name = name;
  16997. result.id = name;
  16998. if (newParent) {
  16999. result.parent = newParent;
  17000. }
  17001. if (!doNotCloneChildren) {
  17002. // Children
  17003. var directDescendants = this.getDescendants(true);
  17004. for (var index = 0; index < directDescendants.length; index++) {
  17005. var child = directDescendants[index];
  17006. if (child.clone) {
  17007. child.clone(name + "." + child.name, result);
  17008. }
  17009. }
  17010. }
  17011. return result;
  17012. };
  17013. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17014. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17015. serializationObject.type = this.getClassName();
  17016. // Parent
  17017. if (this.parent) {
  17018. serializationObject.parentId = this.parent.id;
  17019. }
  17020. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17021. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17022. }
  17023. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17024. serializationObject.isEnabled = this.isEnabled();
  17025. // Parent
  17026. if (this.parent) {
  17027. serializationObject.parentId = this.parent.id;
  17028. }
  17029. return serializationObject;
  17030. };
  17031. // Statics
  17032. /**
  17033. * Returns a new TransformNode object parsed from the source provided.
  17034. * The parameter `parsedMesh` is the source.
  17035. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17036. */
  17037. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17038. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17039. if (BABYLON.Tags) {
  17040. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17041. }
  17042. if (parsedTransformNode.localMatrix) {
  17043. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17044. }
  17045. else if (parsedTransformNode.pivotMatrix) {
  17046. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17047. }
  17048. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17049. // Parent
  17050. if (parsedTransformNode.parentId) {
  17051. transformNode._waitingParentId = parsedTransformNode.parentId;
  17052. }
  17053. return transformNode;
  17054. };
  17055. /**
  17056. * Disposes the TransformNode.
  17057. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17058. * Returns nothing.
  17059. */
  17060. TransformNode.prototype.dispose = function (doNotRecurse) {
  17061. // Animations
  17062. this.getScene().stopAnimation(this);
  17063. // Remove from scene
  17064. this.getScene().removeTransformNode(this);
  17065. if (!doNotRecurse) {
  17066. // Children
  17067. var objects = this.getDescendants(true);
  17068. for (var index = 0; index < objects.length; index++) {
  17069. objects[index].dispose();
  17070. }
  17071. }
  17072. else {
  17073. var childMeshes = this.getChildMeshes(true);
  17074. for (index = 0; index < childMeshes.length; index++) {
  17075. var child = childMeshes[index];
  17076. child.parent = null;
  17077. child.computeWorldMatrix(true);
  17078. }
  17079. }
  17080. this.onAfterWorldMatrixUpdateObservable.clear();
  17081. _super.prototype.dispose.call(this);
  17082. };
  17083. // Statics
  17084. TransformNode.BILLBOARDMODE_NONE = 0;
  17085. TransformNode.BILLBOARDMODE_X = 1;
  17086. TransformNode.BILLBOARDMODE_Y = 2;
  17087. TransformNode.BILLBOARDMODE_Z = 4;
  17088. TransformNode.BILLBOARDMODE_ALL = 7;
  17089. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17090. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17091. __decorate([
  17092. BABYLON.serializeAsVector3()
  17093. ], TransformNode.prototype, "_rotation", void 0);
  17094. __decorate([
  17095. BABYLON.serializeAsQuaternion()
  17096. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17097. __decorate([
  17098. BABYLON.serializeAsVector3()
  17099. ], TransformNode.prototype, "_scaling", void 0);
  17100. __decorate([
  17101. BABYLON.serialize()
  17102. ], TransformNode.prototype, "billboardMode", void 0);
  17103. __decorate([
  17104. BABYLON.serialize()
  17105. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17106. __decorate([
  17107. BABYLON.serialize()
  17108. ], TransformNode.prototype, "infiniteDistance", void 0);
  17109. __decorate([
  17110. BABYLON.serializeAsVector3()
  17111. ], TransformNode.prototype, "position", void 0);
  17112. return TransformNode;
  17113. }(BABYLON.Node));
  17114. BABYLON.TransformNode = TransformNode;
  17115. })(BABYLON || (BABYLON = {}));
  17116. //# sourceMappingURL=babylon.transformNode.js.map
  17117. var BABYLON;
  17118. (function (BABYLON) {
  17119. var AbstractMesh = /** @class */ (function (_super) {
  17120. __extends(AbstractMesh, _super);
  17121. // Constructor
  17122. function AbstractMesh(name, scene) {
  17123. if (scene === void 0) { scene = null; }
  17124. var _this = _super.call(this, name, scene, false) || this;
  17125. _this._facetNb = 0; // facet number
  17126. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17127. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17128. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17129. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17130. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17131. _this._subDiv = {
  17132. max: 1,
  17133. X: 1,
  17134. Y: 1,
  17135. Z: 1
  17136. };
  17137. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17138. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17139. // Events
  17140. /**
  17141. * An event triggered when this mesh collides with another one
  17142. * @type {BABYLON.Observable}
  17143. */
  17144. _this.onCollideObservable = new BABYLON.Observable();
  17145. /**
  17146. * An event triggered when the collision's position changes
  17147. * @type {BABYLON.Observable}
  17148. */
  17149. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17150. /**
  17151. * An event triggered when material is changed
  17152. * @type {BABYLON.Observable}
  17153. */
  17154. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17155. // Properties
  17156. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17157. /**
  17158. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17159. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17160. * or
  17161. * 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.
  17162. * for more info check WebGl documentations
  17163. */
  17164. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17165. /**
  17166. * 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:
  17167. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17168. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17169. * 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.
  17170. */
  17171. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17172. /**
  17173. * 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.
  17174. * The default value is -1 which means don't break the query and wait till the result.
  17175. */
  17176. _this.occlusionRetryCount = -1;
  17177. _this._occlusionInternalRetryCounter = 0;
  17178. _this._isOccluded = false;
  17179. _this._isOcclusionQueryInProgress = false;
  17180. _this._visibility = 1.0;
  17181. _this.alphaIndex = Number.MAX_VALUE;
  17182. _this.isVisible = true;
  17183. _this.isPickable = true;
  17184. _this.showBoundingBox = false;
  17185. _this.showSubMeshesBoundingBox = false;
  17186. _this.isBlocker = false;
  17187. _this.enablePointerMoveEvents = false;
  17188. _this.renderingGroupId = 0;
  17189. _this._receiveShadows = false;
  17190. _this.renderOutline = false;
  17191. _this.outlineColor = BABYLON.Color3.Red();
  17192. _this.outlineWidth = 0.02;
  17193. _this.renderOverlay = false;
  17194. _this.overlayColor = BABYLON.Color3.Red();
  17195. _this.overlayAlpha = 0.5;
  17196. _this._hasVertexAlpha = false;
  17197. _this._useVertexColors = true;
  17198. _this._computeBonesUsingShaders = true;
  17199. _this._numBoneInfluencers = 4;
  17200. _this._applyFog = true;
  17201. _this.useOctreeForRenderingSelection = true;
  17202. _this.useOctreeForPicking = true;
  17203. _this.useOctreeForCollisions = true;
  17204. _this._layerMask = 0x0FFFFFFF;
  17205. /**
  17206. * True if the mesh must be rendered in any case.
  17207. */
  17208. _this.alwaysSelectAsActiveMesh = false;
  17209. /**
  17210. * This scene's action manager
  17211. * @type {BABYLON.ActionManager}
  17212. */
  17213. _this.actionManager = null;
  17214. // Physics
  17215. _this.physicsImpostor = null;
  17216. // Collisions
  17217. _this._checkCollisions = false;
  17218. _this._collisionMask = -1;
  17219. _this._collisionGroup = -1;
  17220. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17221. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17222. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17223. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17224. // Edges
  17225. _this.edgesWidth = 1;
  17226. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17227. // Cache
  17228. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17229. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17230. _this._renderId = 0;
  17231. _this._intersectionsInProgress = new Array();
  17232. _this._unIndexed = false;
  17233. _this._lightSources = new Array();
  17234. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17235. if (collidedMesh === void 0) { collidedMesh = null; }
  17236. //TODO move this to the collision coordinator!
  17237. if (_this.getScene().workerCollisions)
  17238. newPosition.multiplyInPlace(_this._collider._radius);
  17239. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17240. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17241. _this.position.addInPlace(_this._diffPositionForCollisions);
  17242. }
  17243. if (collidedMesh) {
  17244. _this.onCollideObservable.notifyObservers(collidedMesh);
  17245. }
  17246. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17247. };
  17248. _this.getScene().addMesh(_this);
  17249. _this._resyncLightSources();
  17250. return _this;
  17251. }
  17252. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17253. get: function () {
  17254. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17260. get: function () {
  17261. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17262. },
  17263. enumerable: true,
  17264. configurable: true
  17265. });
  17266. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17267. get: function () {
  17268. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17269. },
  17270. enumerable: true,
  17271. configurable: true
  17272. });
  17273. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17274. get: function () {
  17275. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17281. get: function () {
  17282. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17288. /**
  17289. * Read-only : the number of facets in the mesh
  17290. */
  17291. get: function () {
  17292. return this._facetNb;
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17298. /**
  17299. * The number (integer) of subdivisions per axis in the partioning space
  17300. */
  17301. get: function () {
  17302. return this._partitioningSubdivisions;
  17303. },
  17304. set: function (nb) {
  17305. this._partitioningSubdivisions = nb;
  17306. },
  17307. enumerable: true,
  17308. configurable: true
  17309. });
  17310. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17311. /**
  17312. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17313. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17314. */
  17315. get: function () {
  17316. return this._partitioningBBoxRatio;
  17317. },
  17318. set: function (ratio) {
  17319. this._partitioningBBoxRatio = ratio;
  17320. },
  17321. enumerable: true,
  17322. configurable: true
  17323. });
  17324. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17325. /**
  17326. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17327. * Works only for updatable meshes.
  17328. * Doesn't work with multi-materials.
  17329. */
  17330. get: function () {
  17331. return this._facetDepthSort;
  17332. },
  17333. set: function (sort) {
  17334. this._facetDepthSort = sort;
  17335. },
  17336. enumerable: true,
  17337. configurable: true
  17338. });
  17339. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17340. /**
  17341. * The location (Vector3) where the facet depth sort must be computed from.
  17342. * By default, the active camera position.
  17343. * Used only when facet depth sort is enabled.
  17344. */
  17345. get: function () {
  17346. return this._facetDepthSortFrom;
  17347. },
  17348. set: function (location) {
  17349. this._facetDepthSortFrom = location;
  17350. },
  17351. enumerable: true,
  17352. configurable: true
  17353. });
  17354. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17355. /**
  17356. * Read-only boolean : is the feature facetData enabled ?
  17357. */
  17358. get: function () {
  17359. return this._facetDataEnabled;
  17360. },
  17361. enumerable: true,
  17362. configurable: true
  17363. });
  17364. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17365. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17366. return false;
  17367. }
  17368. this._markSubMeshesAsMiscDirty();
  17369. return true;
  17370. };
  17371. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17372. set: function (callback) {
  17373. if (this._onCollideObserver) {
  17374. this.onCollideObservable.remove(this._onCollideObserver);
  17375. }
  17376. this._onCollideObserver = this.onCollideObservable.add(callback);
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17382. set: function (callback) {
  17383. if (this._onCollisionPositionChangeObserver) {
  17384. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17385. }
  17386. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17392. /**
  17393. * 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.
  17394. */
  17395. get: function () {
  17396. return this._isOccluded;
  17397. },
  17398. set: function (value) {
  17399. this._isOccluded = value;
  17400. },
  17401. enumerable: true,
  17402. configurable: true
  17403. });
  17404. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17405. /**
  17406. * Flag to check the progress status of the query
  17407. */
  17408. get: function () {
  17409. return this._isOcclusionQueryInProgress;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17415. /**
  17416. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17417. */
  17418. get: function () {
  17419. return this._visibility;
  17420. },
  17421. /**
  17422. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17423. */
  17424. set: function (value) {
  17425. if (this._visibility === value) {
  17426. return;
  17427. }
  17428. this._visibility = value;
  17429. this._markSubMeshesAsMiscDirty();
  17430. },
  17431. enumerable: true,
  17432. configurable: true
  17433. });
  17434. Object.defineProperty(AbstractMesh.prototype, "material", {
  17435. get: function () {
  17436. return this._material;
  17437. },
  17438. set: function (value) {
  17439. if (this._material === value) {
  17440. return;
  17441. }
  17442. this._material = value;
  17443. if (this.onMaterialChangedObservable.hasObservers) {
  17444. this.onMaterialChangedObservable.notifyObservers(this);
  17445. }
  17446. if (!this.subMeshes) {
  17447. return;
  17448. }
  17449. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17450. var subMesh = _a[_i];
  17451. subMesh.setEffect(null);
  17452. }
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17458. get: function () {
  17459. return this._receiveShadows;
  17460. },
  17461. set: function (value) {
  17462. if (this._receiveShadows === value) {
  17463. return;
  17464. }
  17465. this._receiveShadows = value;
  17466. this._markSubMeshesAsLightDirty();
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17472. get: function () {
  17473. return this._hasVertexAlpha;
  17474. },
  17475. set: function (value) {
  17476. if (this._hasVertexAlpha === value) {
  17477. return;
  17478. }
  17479. this._hasVertexAlpha = value;
  17480. this._markSubMeshesAsAttributesDirty();
  17481. this._markSubMeshesAsMiscDirty();
  17482. },
  17483. enumerable: true,
  17484. configurable: true
  17485. });
  17486. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17487. get: function () {
  17488. return this._useVertexColors;
  17489. },
  17490. set: function (value) {
  17491. if (this._useVertexColors === value) {
  17492. return;
  17493. }
  17494. this._useVertexColors = value;
  17495. this._markSubMeshesAsAttributesDirty();
  17496. },
  17497. enumerable: true,
  17498. configurable: true
  17499. });
  17500. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17501. get: function () {
  17502. return this._computeBonesUsingShaders;
  17503. },
  17504. set: function (value) {
  17505. if (this._computeBonesUsingShaders === value) {
  17506. return;
  17507. }
  17508. this._computeBonesUsingShaders = value;
  17509. this._markSubMeshesAsAttributesDirty();
  17510. },
  17511. enumerable: true,
  17512. configurable: true
  17513. });
  17514. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17515. get: function () {
  17516. return this._numBoneInfluencers;
  17517. },
  17518. set: function (value) {
  17519. if (this._numBoneInfluencers === value) {
  17520. return;
  17521. }
  17522. this._numBoneInfluencers = value;
  17523. this._markSubMeshesAsAttributesDirty();
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17529. get: function () {
  17530. return this._applyFog;
  17531. },
  17532. set: function (value) {
  17533. if (this._applyFog === value) {
  17534. return;
  17535. }
  17536. this._applyFog = value;
  17537. this._markSubMeshesAsMiscDirty();
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17543. get: function () {
  17544. return this._layerMask;
  17545. },
  17546. set: function (value) {
  17547. if (value === this._layerMask) {
  17548. return;
  17549. }
  17550. this._layerMask = value;
  17551. this._resyncLightSources();
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17557. get: function () {
  17558. return this._collisionMask;
  17559. },
  17560. set: function (mask) {
  17561. this._collisionMask = !isNaN(mask) ? mask : -1;
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17567. get: function () {
  17568. return this._collisionGroup;
  17569. },
  17570. set: function (mask) {
  17571. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17572. },
  17573. enumerable: true,
  17574. configurable: true
  17575. });
  17576. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17577. get: function () {
  17578. return null;
  17579. },
  17580. enumerable: true,
  17581. configurable: true
  17582. });
  17583. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17584. get: function () {
  17585. return this._skeleton;
  17586. },
  17587. set: function (value) {
  17588. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17589. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17590. }
  17591. if (value && value.needInitialSkinMatrix) {
  17592. value._registerMeshWithPoseMatrix(this);
  17593. }
  17594. this._skeleton = value;
  17595. if (!this._skeleton) {
  17596. this._bonesTransformMatrices = null;
  17597. }
  17598. this._markSubMeshesAsAttributesDirty();
  17599. },
  17600. enumerable: true,
  17601. configurable: true
  17602. });
  17603. /**
  17604. * Returns the string "AbstractMesh"
  17605. */
  17606. AbstractMesh.prototype.getClassName = function () {
  17607. return "AbstractMesh";
  17608. };
  17609. /**
  17610. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17611. */
  17612. AbstractMesh.prototype.toString = function (fullDetails) {
  17613. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17614. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17615. if (this._skeleton) {
  17616. ret += ", skeleton: " + this._skeleton.name;
  17617. }
  17618. if (fullDetails) {
  17619. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17620. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17621. }
  17622. return ret;
  17623. };
  17624. AbstractMesh.prototype._rebuild = function () {
  17625. if (this._occlusionQuery) {
  17626. this._occlusionQuery = null;
  17627. }
  17628. if (this._edgesRenderer) {
  17629. this._edgesRenderer._rebuild();
  17630. }
  17631. if (!this.subMeshes) {
  17632. return;
  17633. }
  17634. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17635. var subMesh = _a[_i];
  17636. subMesh._rebuild();
  17637. }
  17638. };
  17639. AbstractMesh.prototype._resyncLightSources = function () {
  17640. this._lightSources.length = 0;
  17641. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17642. var light = _a[_i];
  17643. if (!light.isEnabled()) {
  17644. continue;
  17645. }
  17646. if (light.canAffectMesh(this)) {
  17647. this._lightSources.push(light);
  17648. }
  17649. }
  17650. this._markSubMeshesAsLightDirty();
  17651. };
  17652. AbstractMesh.prototype._resyncLighSource = function (light) {
  17653. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17654. var index = this._lightSources.indexOf(light);
  17655. if (index === -1) {
  17656. if (!isIn) {
  17657. return;
  17658. }
  17659. this._lightSources.push(light);
  17660. }
  17661. else {
  17662. if (isIn) {
  17663. return;
  17664. }
  17665. this._lightSources.splice(index, 1);
  17666. }
  17667. this._markSubMeshesAsLightDirty();
  17668. };
  17669. AbstractMesh.prototype._removeLightSource = function (light) {
  17670. var index = this._lightSources.indexOf(light);
  17671. if (index === -1) {
  17672. return;
  17673. }
  17674. this._lightSources.splice(index, 1);
  17675. this._markSubMeshesAsLightDirty();
  17676. };
  17677. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17678. if (!this.subMeshes) {
  17679. return;
  17680. }
  17681. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17682. var subMesh = _a[_i];
  17683. if (subMesh._materialDefines) {
  17684. func(subMesh._materialDefines);
  17685. }
  17686. }
  17687. };
  17688. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17689. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17690. };
  17691. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17692. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17693. };
  17694. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17695. if (!this.subMeshes) {
  17696. return;
  17697. }
  17698. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17699. var subMesh = _a[_i];
  17700. var material = subMesh.getMaterial();
  17701. if (material) {
  17702. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17703. }
  17704. }
  17705. };
  17706. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17707. /**
  17708. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17709. * Default : (1.0, 1.0, 1.0)
  17710. */
  17711. get: function () {
  17712. return this._scaling;
  17713. },
  17714. /**
  17715. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17716. * Default : (1.0, 1.0, 1.0)
  17717. */
  17718. set: function (newScaling) {
  17719. this._scaling = newScaling;
  17720. if (this.physicsImpostor) {
  17721. this.physicsImpostor.forceUpdate();
  17722. }
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. // Methods
  17728. /**
  17729. * Disables the mesh edger rendering mode.
  17730. * Returns the AbstractMesh.
  17731. */
  17732. AbstractMesh.prototype.disableEdgesRendering = function () {
  17733. if (this._edgesRenderer) {
  17734. this._edgesRenderer.dispose();
  17735. this._edgesRenderer = null;
  17736. }
  17737. return this;
  17738. };
  17739. /**
  17740. * Enables the edge rendering mode on the mesh.
  17741. * This mode makes the mesh edges visible.
  17742. * Returns the AbstractMesh.
  17743. */
  17744. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17745. if (epsilon === void 0) { epsilon = 0.95; }
  17746. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17747. this.disableEdgesRendering();
  17748. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17749. return this;
  17750. };
  17751. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17752. /**
  17753. * Returns true if the mesh is blocked. Used by the class Mesh.
  17754. * Returns the boolean `false` by default.
  17755. */
  17756. get: function () {
  17757. return false;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. /**
  17763. * Returns the mesh itself by default, used by the class Mesh.
  17764. * Returned type : AbstractMesh
  17765. */
  17766. AbstractMesh.prototype.getLOD = function (camera) {
  17767. return this;
  17768. };
  17769. /**
  17770. * Returns 0 by default, used by the class Mesh.
  17771. * Returns an integer.
  17772. */
  17773. AbstractMesh.prototype.getTotalVertices = function () {
  17774. return 0;
  17775. };
  17776. /**
  17777. * Returns null by default, used by the class Mesh.
  17778. * Returned type : integer array
  17779. */
  17780. AbstractMesh.prototype.getIndices = function () {
  17781. return null;
  17782. };
  17783. /**
  17784. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17785. * Returned type : float array or Float32Array
  17786. */
  17787. AbstractMesh.prototype.getVerticesData = function (kind) {
  17788. return null;
  17789. };
  17790. /**
  17791. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17792. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17793. * The `data` are either a numeric array either a Float32Array.
  17794. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17795. * 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).
  17796. * Note that a new underlying VertexBuffer object is created each call.
  17797. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17798. *
  17799. * Possible `kind` values :
  17800. * - BABYLON.VertexBuffer.PositionKind
  17801. * - BABYLON.VertexBuffer.UVKind
  17802. * - BABYLON.VertexBuffer.UV2Kind
  17803. * - BABYLON.VertexBuffer.UV3Kind
  17804. * - BABYLON.VertexBuffer.UV4Kind
  17805. * - BABYLON.VertexBuffer.UV5Kind
  17806. * - BABYLON.VertexBuffer.UV6Kind
  17807. * - BABYLON.VertexBuffer.ColorKind
  17808. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17809. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17810. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17811. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17812. *
  17813. * Returns the Mesh.
  17814. */
  17815. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17816. return this;
  17817. };
  17818. /**
  17819. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17820. * If the mesh has no geometry, it is simply returned as it is.
  17821. * The `data` are either a numeric array either a Float32Array.
  17822. * No new underlying VertexBuffer object is created.
  17823. * 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.
  17824. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17825. *
  17826. * Possible `kind` values :
  17827. * - BABYLON.VertexBuffer.PositionKind
  17828. * - BABYLON.VertexBuffer.UVKind
  17829. * - BABYLON.VertexBuffer.UV2Kind
  17830. * - BABYLON.VertexBuffer.UV3Kind
  17831. * - BABYLON.VertexBuffer.UV4Kind
  17832. * - BABYLON.VertexBuffer.UV5Kind
  17833. * - BABYLON.VertexBuffer.UV6Kind
  17834. * - BABYLON.VertexBuffer.ColorKind
  17835. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17836. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17837. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17838. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17839. *
  17840. * Returns the Mesh.
  17841. */
  17842. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17843. return this;
  17844. };
  17845. /**
  17846. * Sets the mesh indices.
  17847. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17848. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17849. * This method creates a new index buffer each call.
  17850. * Returns the Mesh.
  17851. */
  17852. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17853. return this;
  17854. };
  17855. /** Returns false by default, used by the class Mesh.
  17856. * Returns a boolean
  17857. */
  17858. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17859. return false;
  17860. };
  17861. /**
  17862. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17863. * Returns a BoundingInfo
  17864. */
  17865. AbstractMesh.prototype.getBoundingInfo = function () {
  17866. if (this._masterMesh) {
  17867. return this._masterMesh.getBoundingInfo();
  17868. }
  17869. if (!this._boundingInfo) {
  17870. // this._boundingInfo is being created here
  17871. this._updateBoundingInfo();
  17872. }
  17873. // cannot be null.
  17874. return this._boundingInfo;
  17875. };
  17876. /**
  17877. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17878. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17879. */
  17880. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17881. if (includeDescendants === void 0) { includeDescendants = true; }
  17882. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17883. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17884. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17885. if (maxDimension === 0) {
  17886. return this;
  17887. }
  17888. var scale = 1 / maxDimension;
  17889. this.scaling.scaleInPlace(scale);
  17890. return this;
  17891. };
  17892. /**
  17893. * Sets a mesh new object BoundingInfo.
  17894. * Returns the AbstractMesh.
  17895. */
  17896. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17897. this._boundingInfo = boundingInfo;
  17898. return this;
  17899. };
  17900. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17901. get: function () {
  17902. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. AbstractMesh.prototype._preActivate = function () {
  17908. };
  17909. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17910. };
  17911. AbstractMesh.prototype._activate = function (renderId) {
  17912. this._renderId = renderId;
  17913. };
  17914. /**
  17915. * Returns the latest update of the World matrix
  17916. * Returns a Matrix.
  17917. */
  17918. AbstractMesh.prototype.getWorldMatrix = function () {
  17919. if (this._masterMesh) {
  17920. return this._masterMesh.getWorldMatrix();
  17921. }
  17922. return _super.prototype.getWorldMatrix.call(this);
  17923. };
  17924. /**
  17925. * Returns the latest update of the World matrix determinant.
  17926. */
  17927. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17928. if (this._masterMesh) {
  17929. return this._masterMesh._getWorldMatrixDeterminant();
  17930. }
  17931. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17932. };
  17933. // ================================== Point of View Movement =================================
  17934. /**
  17935. * Perform relative position change from the point of view of behind the front of the mesh.
  17936. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17937. * Supports definition of mesh facing forward or backward.
  17938. * @param {number} amountRight
  17939. * @param {number} amountUp
  17940. * @param {number} amountForward
  17941. *
  17942. * Returns the AbstractMesh.
  17943. */
  17944. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17945. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17946. return this;
  17947. };
  17948. /**
  17949. * Calculate relative position change from the point of view of behind the front of the mesh.
  17950. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17951. * Supports definition of mesh facing forward or backward.
  17952. * @param {number} amountRight
  17953. * @param {number} amountUp
  17954. * @param {number} amountForward
  17955. *
  17956. * Returns a new Vector3.
  17957. */
  17958. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17959. var rotMatrix = new BABYLON.Matrix();
  17960. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17961. rotQuaternion.toRotationMatrix(rotMatrix);
  17962. var translationDelta = BABYLON.Vector3.Zero();
  17963. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17964. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17965. return translationDelta;
  17966. };
  17967. // ================================== Point of View Rotation =================================
  17968. /**
  17969. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17970. * Supports definition of mesh facing forward or backward.
  17971. * @param {number} flipBack
  17972. * @param {number} twirlClockwise
  17973. * @param {number} tiltRight
  17974. *
  17975. * Returns the AbstractMesh.
  17976. */
  17977. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17978. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17979. return this;
  17980. };
  17981. /**
  17982. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17983. * Supports definition of mesh facing forward or backward.
  17984. * @param {number} flipBack
  17985. * @param {number} twirlClockwise
  17986. * @param {number} tiltRight
  17987. *
  17988. * Returns a new Vector3.
  17989. */
  17990. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17991. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17992. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17993. };
  17994. /**
  17995. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17996. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17997. */
  17998. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17999. if (includeDescendants === void 0) { includeDescendants = true; }
  18000. this.computeWorldMatrix(true);
  18001. var min;
  18002. var max;
  18003. var boundingInfo = this.getBoundingInfo();
  18004. if (!this.subMeshes) {
  18005. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18006. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18007. }
  18008. else {
  18009. min = boundingInfo.boundingBox.minimumWorld;
  18010. max = boundingInfo.boundingBox.maximumWorld;
  18011. }
  18012. if (includeDescendants) {
  18013. var descendants = this.getDescendants(false);
  18014. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18015. var descendant = descendants_1[_i];
  18016. var childMesh = descendant;
  18017. childMesh.computeWorldMatrix(true);
  18018. //make sure we have the needed params to get mix and max
  18019. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18020. continue;
  18021. }
  18022. var childBoundingInfo = childMesh.getBoundingInfo();
  18023. var boundingBox = childBoundingInfo.boundingBox;
  18024. var minBox = boundingBox.minimumWorld;
  18025. var maxBox = boundingBox.maximumWorld;
  18026. BABYLON.Tools.CheckExtends(minBox, min, max);
  18027. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18028. }
  18029. }
  18030. return {
  18031. min: min,
  18032. max: max
  18033. };
  18034. };
  18035. /**
  18036. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18037. * Returns the AbstractMesh.
  18038. */
  18039. AbstractMesh.prototype._updateBoundingInfo = function () {
  18040. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18041. this._boundingInfo.update(this.worldMatrixFromCache);
  18042. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18043. return this;
  18044. };
  18045. /**
  18046. * Update a mesh's children BoundingInfo objects only.
  18047. * Returns the AbstractMesh.
  18048. */
  18049. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18050. if (!this.subMeshes) {
  18051. return this;
  18052. }
  18053. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18054. var subMesh = this.subMeshes[subIndex];
  18055. if (!subMesh.IsGlobal) {
  18056. subMesh.updateBoundingInfo(matrix);
  18057. }
  18058. }
  18059. return this;
  18060. };
  18061. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18062. // Bounding info
  18063. this._updateBoundingInfo();
  18064. };
  18065. /**
  18066. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18067. * A mesh is in the frustum if its bounding box intersects the frustum.
  18068. * Boolean returned.
  18069. */
  18070. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18071. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18072. };
  18073. /**
  18074. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18075. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18076. * Boolean returned.
  18077. */
  18078. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18079. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18080. ;
  18081. };
  18082. /**
  18083. * True if the mesh intersects another mesh or a SolidParticle object.
  18084. * 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)
  18085. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18086. * Returns a boolean.
  18087. */
  18088. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18089. if (precise === void 0) { precise = false; }
  18090. if (!this._boundingInfo || !mesh._boundingInfo) {
  18091. return false;
  18092. }
  18093. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18094. return true;
  18095. }
  18096. if (includeDescendants) {
  18097. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18098. var child = _a[_i];
  18099. if (child.intersectsMesh(mesh, precise, true)) {
  18100. return true;
  18101. }
  18102. }
  18103. }
  18104. return false;
  18105. };
  18106. /**
  18107. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18108. * Returns a boolean.
  18109. */
  18110. AbstractMesh.prototype.intersectsPoint = function (point) {
  18111. if (!this._boundingInfo) {
  18112. return false;
  18113. }
  18114. return this._boundingInfo.intersectsPoint(point);
  18115. };
  18116. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18117. return this.physicsImpostor;
  18118. };
  18119. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18120. if (camera === void 0) { camera = null; }
  18121. if (!camera) {
  18122. camera = this.getScene().activeCamera;
  18123. }
  18124. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18125. };
  18126. /**
  18127. * Returns the distance from the mesh to the active camera.
  18128. * Returns a float.
  18129. */
  18130. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18131. if (camera === void 0) { camera = null; }
  18132. if (!camera) {
  18133. camera = this.getScene().activeCamera;
  18134. }
  18135. return this.absolutePosition.subtract(camera.position).length();
  18136. };
  18137. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18138. if (!this.physicsImpostor) {
  18139. return this;
  18140. }
  18141. this.physicsImpostor.applyImpulse(force, contactPoint);
  18142. return this;
  18143. };
  18144. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18145. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18146. return this;
  18147. }
  18148. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18149. mainPivot: pivot1,
  18150. connectedPivot: pivot2,
  18151. nativeParams: options
  18152. });
  18153. return this;
  18154. };
  18155. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18156. // Collisions
  18157. /**
  18158. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18159. * Default `false`.
  18160. */
  18161. get: function () {
  18162. return this._checkCollisions;
  18163. },
  18164. set: function (collisionEnabled) {
  18165. this._checkCollisions = collisionEnabled;
  18166. if (this.getScene().workerCollisions) {
  18167. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18168. }
  18169. },
  18170. enumerable: true,
  18171. configurable: true
  18172. });
  18173. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18174. /**
  18175. * Gets Collider object used to compute collisions (not physics)
  18176. */
  18177. get: function () {
  18178. return this._collider;
  18179. },
  18180. enumerable: true,
  18181. configurable: true
  18182. });
  18183. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18184. var globalPosition = this.getAbsolutePosition();
  18185. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18186. if (!this._collider) {
  18187. this._collider = new BABYLON.Collider();
  18188. }
  18189. this._collider._radius = this.ellipsoid;
  18190. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18191. return this;
  18192. };
  18193. // Submeshes octree
  18194. /**
  18195. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18196. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18197. * Returns an Octree of submeshes.
  18198. */
  18199. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18200. if (maxCapacity === void 0) { maxCapacity = 64; }
  18201. if (maxDepth === void 0) { maxDepth = 2; }
  18202. if (!this._submeshesOctree) {
  18203. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18204. }
  18205. this.computeWorldMatrix(true);
  18206. var boundingInfo = this.getBoundingInfo();
  18207. // Update octree
  18208. var bbox = boundingInfo.boundingBox;
  18209. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18210. return this._submeshesOctree;
  18211. };
  18212. // Collisions
  18213. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18214. this._generatePointsArray();
  18215. if (!this._positions) {
  18216. return this;
  18217. }
  18218. // Transformation
  18219. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18220. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18221. subMesh._lastColliderWorldVertices = [];
  18222. subMesh._trianglePlanes = [];
  18223. var start = subMesh.verticesStart;
  18224. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18225. for (var i = start; i < end; i++) {
  18226. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18227. }
  18228. }
  18229. // Collide
  18230. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18231. if (collider.collisionFound) {
  18232. collider.collidedMesh = this;
  18233. }
  18234. return this;
  18235. };
  18236. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18237. var subMeshes;
  18238. var len;
  18239. // Octrees
  18240. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18241. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18242. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18243. len = intersections.length;
  18244. subMeshes = intersections.data;
  18245. }
  18246. else {
  18247. subMeshes = this.subMeshes;
  18248. len = subMeshes.length;
  18249. }
  18250. for (var index = 0; index < len; index++) {
  18251. var subMesh = subMeshes[index];
  18252. // Bounding test
  18253. if (len > 1 && !subMesh._checkCollision(collider))
  18254. continue;
  18255. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18256. }
  18257. return this;
  18258. };
  18259. AbstractMesh.prototype._checkCollision = function (collider) {
  18260. // Bounding box test
  18261. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18262. return this;
  18263. // Transformation matrix
  18264. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18265. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18266. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18267. return this;
  18268. };
  18269. // Picking
  18270. AbstractMesh.prototype._generatePointsArray = function () {
  18271. return false;
  18272. };
  18273. /**
  18274. * Checks if the passed Ray intersects with the mesh.
  18275. * Returns an object PickingInfo.
  18276. */
  18277. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18278. var pickingInfo = new BABYLON.PickingInfo();
  18279. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18280. return pickingInfo;
  18281. }
  18282. if (!this._generatePointsArray()) {
  18283. return pickingInfo;
  18284. }
  18285. var intersectInfo = null;
  18286. // Octrees
  18287. var subMeshes;
  18288. var len;
  18289. if (this._submeshesOctree && this.useOctreeForPicking) {
  18290. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18291. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18292. len = intersections.length;
  18293. subMeshes = intersections.data;
  18294. }
  18295. else {
  18296. subMeshes = this.subMeshes;
  18297. len = subMeshes.length;
  18298. }
  18299. for (var index = 0; index < len; index++) {
  18300. var subMesh = subMeshes[index];
  18301. // Bounding test
  18302. if (len > 1 && !subMesh.canIntersects(ray))
  18303. continue;
  18304. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18305. if (currentIntersectInfo) {
  18306. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18307. intersectInfo = currentIntersectInfo;
  18308. intersectInfo.subMeshId = index;
  18309. if (fastCheck) {
  18310. break;
  18311. }
  18312. }
  18313. }
  18314. }
  18315. if (intersectInfo) {
  18316. // Get picked point
  18317. var world = this.getWorldMatrix();
  18318. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18319. var direction = ray.direction.clone();
  18320. direction = direction.scale(intersectInfo.distance);
  18321. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18322. var pickedPoint = worldOrigin.add(worldDirection);
  18323. // Return result
  18324. pickingInfo.hit = true;
  18325. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18326. pickingInfo.pickedPoint = pickedPoint;
  18327. pickingInfo.pickedMesh = this;
  18328. pickingInfo.bu = intersectInfo.bu || 0;
  18329. pickingInfo.bv = intersectInfo.bv || 0;
  18330. pickingInfo.faceId = intersectInfo.faceId;
  18331. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18332. return pickingInfo;
  18333. }
  18334. return pickingInfo;
  18335. };
  18336. /**
  18337. * Clones the mesh, used by the class Mesh.
  18338. * Just returns `null` for an AbstractMesh.
  18339. */
  18340. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18341. return null;
  18342. };
  18343. /**
  18344. * Disposes all the mesh submeshes.
  18345. * Returns the AbstractMesh.
  18346. */
  18347. AbstractMesh.prototype.releaseSubMeshes = function () {
  18348. if (this.subMeshes) {
  18349. while (this.subMeshes.length) {
  18350. this.subMeshes[0].dispose();
  18351. }
  18352. }
  18353. else {
  18354. this.subMeshes = new Array();
  18355. }
  18356. return this;
  18357. };
  18358. /**
  18359. * Disposes the AbstractMesh.
  18360. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18361. * Returns nothing.
  18362. */
  18363. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18364. var _this = this;
  18365. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18366. var index;
  18367. // Action manager
  18368. if (this.actionManager !== undefined && this.actionManager !== null) {
  18369. this.actionManager.dispose();
  18370. this.actionManager = null;
  18371. }
  18372. // Skeleton
  18373. this.skeleton = null;
  18374. // Physics
  18375. if (this.physicsImpostor) {
  18376. this.physicsImpostor.dispose();
  18377. }
  18378. // Intersections in progress
  18379. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18380. var other = this._intersectionsInProgress[index];
  18381. var pos = other._intersectionsInProgress.indexOf(this);
  18382. other._intersectionsInProgress.splice(pos, 1);
  18383. }
  18384. this._intersectionsInProgress = [];
  18385. // Lights
  18386. var lights = this.getScene().lights;
  18387. lights.forEach(function (light) {
  18388. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18389. if (meshIndex !== -1) {
  18390. light.includedOnlyMeshes.splice(meshIndex, 1);
  18391. }
  18392. meshIndex = light.excludedMeshes.indexOf(_this);
  18393. if (meshIndex !== -1) {
  18394. light.excludedMeshes.splice(meshIndex, 1);
  18395. }
  18396. // Shadow generators
  18397. var generator = light.getShadowGenerator();
  18398. if (generator) {
  18399. var shadowMap = generator.getShadowMap();
  18400. if (shadowMap && shadowMap.renderList) {
  18401. meshIndex = shadowMap.renderList.indexOf(_this);
  18402. if (meshIndex !== -1) {
  18403. shadowMap.renderList.splice(meshIndex, 1);
  18404. }
  18405. }
  18406. }
  18407. });
  18408. // Edges
  18409. if (this._edgesRenderer) {
  18410. this._edgesRenderer.dispose();
  18411. this._edgesRenderer = null;
  18412. }
  18413. // SubMeshes
  18414. if (this.getClassName() !== "InstancedMesh") {
  18415. this.releaseSubMeshes();
  18416. }
  18417. // Octree
  18418. var sceneOctree = this.getScene().selectionOctree;
  18419. if (sceneOctree !== undefined && sceneOctree !== null) {
  18420. var index = sceneOctree.dynamicContent.indexOf(this);
  18421. if (index !== -1) {
  18422. sceneOctree.dynamicContent.splice(index, 1);
  18423. }
  18424. }
  18425. // Query
  18426. var engine = this.getScene().getEngine();
  18427. if (this._occlusionQuery) {
  18428. this._isOcclusionQueryInProgress = false;
  18429. engine.deleteQuery(this._occlusionQuery);
  18430. this._occlusionQuery = null;
  18431. }
  18432. // Engine
  18433. engine.wipeCaches();
  18434. // Remove from scene
  18435. this.getScene().removeMesh(this);
  18436. if (disposeMaterialAndTextures) {
  18437. if (this.material) {
  18438. this.material.dispose(false, true);
  18439. }
  18440. }
  18441. if (!doNotRecurse) {
  18442. // Particles
  18443. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18444. if (this.getScene().particleSystems[index].emitter === this) {
  18445. this.getScene().particleSystems[index].dispose();
  18446. index--;
  18447. }
  18448. }
  18449. }
  18450. // facet data
  18451. if (this._facetDataEnabled) {
  18452. this.disableFacetData();
  18453. }
  18454. this.onAfterWorldMatrixUpdateObservable.clear();
  18455. this.onCollideObservable.clear();
  18456. this.onCollisionPositionChangeObservable.clear();
  18457. _super.prototype.dispose.call(this, doNotRecurse);
  18458. };
  18459. /**
  18460. * Adds the passed mesh as a child to the current mesh.
  18461. * Returns the AbstractMesh.
  18462. */
  18463. AbstractMesh.prototype.addChild = function (mesh) {
  18464. mesh.setParent(this);
  18465. return this;
  18466. };
  18467. /**
  18468. * Removes the passed mesh from the current mesh children list.
  18469. * Returns the AbstractMesh.
  18470. */
  18471. AbstractMesh.prototype.removeChild = function (mesh) {
  18472. mesh.setParent(null);
  18473. return this;
  18474. };
  18475. // Facet data
  18476. /**
  18477. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18478. * Returns the AbstractMesh.
  18479. */
  18480. AbstractMesh.prototype._initFacetData = function () {
  18481. if (!this._facetNormals) {
  18482. this._facetNormals = new Array();
  18483. }
  18484. if (!this._facetPositions) {
  18485. this._facetPositions = new Array();
  18486. }
  18487. if (!this._facetPartitioning) {
  18488. this._facetPartitioning = new Array();
  18489. }
  18490. this._facetNb = (this.getIndices().length / 3) | 0;
  18491. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18492. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18493. for (var f = 0; f < this._facetNb; f++) {
  18494. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18495. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18496. }
  18497. this._facetDataEnabled = true;
  18498. return this;
  18499. };
  18500. /**
  18501. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18502. * This method can be called within the render loop.
  18503. * 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.
  18504. * Returns the AbstractMesh.
  18505. */
  18506. AbstractMesh.prototype.updateFacetData = function () {
  18507. if (!this._facetDataEnabled) {
  18508. this._initFacetData();
  18509. }
  18510. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18511. var indices = this.getIndices();
  18512. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18513. var bInfo = this.getBoundingInfo();
  18514. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18515. // init arrays, matrix and sort function on first call
  18516. this._facetDepthSortEnabled = true;
  18517. if (indices instanceof Uint16Array) {
  18518. this._depthSortedIndices = new Uint16Array(indices);
  18519. }
  18520. else if (indices instanceof Uint32Array) {
  18521. this._depthSortedIndices = new Uint32Array(indices);
  18522. }
  18523. else {
  18524. var needs32bits = false;
  18525. for (var i = 0; i < indices.length; i++) {
  18526. if (indices[i] > 65535) {
  18527. needs32bits = true;
  18528. break;
  18529. }
  18530. }
  18531. if (needs32bits) {
  18532. this._depthSortedIndices = new Uint32Array(indices);
  18533. }
  18534. else {
  18535. this._depthSortedIndices = new Uint16Array(indices);
  18536. }
  18537. }
  18538. this._facetDepthSortFunction = function (f1, f2) {
  18539. return (f2.sqDistance - f1.sqDistance);
  18540. };
  18541. if (!this._facetDepthSortFrom) {
  18542. var camera = this.getScene().activeCamera;
  18543. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18544. }
  18545. this._depthSortedFacets = [];
  18546. for (var f = 0; f < this._facetNb; f++) {
  18547. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18548. this._depthSortedFacets.push(depthSortedFacet);
  18549. }
  18550. this._invertedMatrix = BABYLON.Matrix.Identity();
  18551. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18552. }
  18553. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18554. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18555. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18556. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18557. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18558. this._subDiv.max = this._partitioningSubdivisions;
  18559. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18560. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18561. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18562. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18563. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18564. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18565. // set the parameters for ComputeNormals()
  18566. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18567. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18568. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18569. this._facetParameters.bInfo = bInfo;
  18570. this._facetParameters.bbSize = this._bbSize;
  18571. this._facetParameters.subDiv = this._subDiv;
  18572. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18573. this._facetParameters.depthSort = this._facetDepthSort;
  18574. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18575. this.computeWorldMatrix(true);
  18576. this._worldMatrix.invertToRef(this._invertedMatrix);
  18577. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18578. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18579. }
  18580. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18581. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18582. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18583. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18584. var l = (this._depthSortedIndices.length / 3) | 0;
  18585. for (var f = 0; f < l; f++) {
  18586. var sind = this._depthSortedFacets[f].ind;
  18587. this._depthSortedIndices[f * 3] = indices[sind];
  18588. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18589. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18590. }
  18591. this.updateIndices(this._depthSortedIndices);
  18592. }
  18593. return this;
  18594. };
  18595. /**
  18596. * Returns the facetLocalNormals array.
  18597. * The normals are expressed in the mesh local space.
  18598. */
  18599. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18600. if (!this._facetNormals) {
  18601. this.updateFacetData();
  18602. }
  18603. return this._facetNormals;
  18604. };
  18605. /**
  18606. * Returns the facetLocalPositions array.
  18607. * The facet positions are expressed in the mesh local space.
  18608. */
  18609. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18610. if (!this._facetPositions) {
  18611. this.updateFacetData();
  18612. }
  18613. return this._facetPositions;
  18614. };
  18615. /**
  18616. * Returns the facetLocalPartioning array.
  18617. */
  18618. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18619. if (!this._facetPartitioning) {
  18620. this.updateFacetData();
  18621. }
  18622. return this._facetPartitioning;
  18623. };
  18624. /**
  18625. * Returns the i-th facet position in the world system.
  18626. * This method allocates a new Vector3 per call.
  18627. */
  18628. AbstractMesh.prototype.getFacetPosition = function (i) {
  18629. var pos = BABYLON.Vector3.Zero();
  18630. this.getFacetPositionToRef(i, pos);
  18631. return pos;
  18632. };
  18633. /**
  18634. * Sets the reference Vector3 with the i-th facet position in the world system.
  18635. * Returns the AbstractMesh.
  18636. */
  18637. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18638. var localPos = (this.getFacetLocalPositions())[i];
  18639. var world = this.getWorldMatrix();
  18640. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18641. return this;
  18642. };
  18643. /**
  18644. * Returns the i-th facet normal in the world system.
  18645. * This method allocates a new Vector3 per call.
  18646. */
  18647. AbstractMesh.prototype.getFacetNormal = function (i) {
  18648. var norm = BABYLON.Vector3.Zero();
  18649. this.getFacetNormalToRef(i, norm);
  18650. return norm;
  18651. };
  18652. /**
  18653. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18654. * Returns the AbstractMesh.
  18655. */
  18656. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18657. var localNorm = (this.getFacetLocalNormals())[i];
  18658. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18659. return this;
  18660. };
  18661. /**
  18662. * 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).
  18663. */
  18664. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18665. var bInfo = this.getBoundingInfo();
  18666. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18667. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18668. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18669. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18670. return null;
  18671. }
  18672. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18673. };
  18674. /**
  18675. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18676. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18677. * 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.
  18678. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18679. * 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.
  18680. */
  18681. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18682. if (checkFace === void 0) { checkFace = false; }
  18683. if (facing === void 0) { facing = true; }
  18684. var world = this.getWorldMatrix();
  18685. var invMat = BABYLON.Tmp.Matrix[5];
  18686. world.invertToRef(invMat);
  18687. var invVect = BABYLON.Tmp.Vector3[8];
  18688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18689. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18690. if (projected) {
  18691. // tranform the local computed projected vector to world coordinates
  18692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18693. }
  18694. return closest;
  18695. };
  18696. /**
  18697. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18698. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18699. * 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.
  18700. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18701. * 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.
  18702. */
  18703. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18704. if (checkFace === void 0) { checkFace = false; }
  18705. if (facing === void 0) { facing = true; }
  18706. var closest = null;
  18707. var tmpx = 0.0;
  18708. var tmpy = 0.0;
  18709. var tmpz = 0.0;
  18710. var d = 0.0; // tmp dot facet normal * facet position
  18711. var t0 = 0.0;
  18712. var projx = 0.0;
  18713. var projy = 0.0;
  18714. var projz = 0.0;
  18715. // Get all the facets in the same partitioning block than (x, y, z)
  18716. var facetPositions = this.getFacetLocalPositions();
  18717. var facetNormals = this.getFacetLocalNormals();
  18718. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18719. if (!facetsInBlock) {
  18720. return null;
  18721. }
  18722. // Get the closest facet to (x, y, z)
  18723. var shortest = Number.MAX_VALUE; // init distance vars
  18724. var tmpDistance = shortest;
  18725. var fib; // current facet in the block
  18726. var norm; // current facet normal
  18727. var p0; // current facet barycenter position
  18728. // loop on all the facets in the current partitioning block
  18729. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18730. fib = facetsInBlock[idx];
  18731. norm = facetNormals[fib];
  18732. p0 = facetPositions[fib];
  18733. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18734. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18735. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18736. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18737. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18738. projx = x + norm.x * t0;
  18739. projy = y + norm.y * t0;
  18740. projz = z + norm.z * t0;
  18741. tmpx = projx - x;
  18742. tmpy = projy - y;
  18743. tmpz = projz - z;
  18744. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18745. if (tmpDistance < shortest) {
  18746. shortest = tmpDistance;
  18747. closest = fib;
  18748. if (projected) {
  18749. projected.x = projx;
  18750. projected.y = projy;
  18751. projected.z = projz;
  18752. }
  18753. }
  18754. }
  18755. }
  18756. return closest;
  18757. };
  18758. /**
  18759. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18760. */
  18761. AbstractMesh.prototype.getFacetDataParameters = function () {
  18762. return this._facetParameters;
  18763. };
  18764. /**
  18765. * Disables the feature FacetData and frees the related memory.
  18766. * Returns the AbstractMesh.
  18767. */
  18768. AbstractMesh.prototype.disableFacetData = function () {
  18769. if (this._facetDataEnabled) {
  18770. this._facetDataEnabled = false;
  18771. this._facetPositions = new Array();
  18772. this._facetNormals = new Array();
  18773. this._facetPartitioning = new Array();
  18774. this._facetParameters = null;
  18775. this._depthSortedIndices = new Uint32Array(0);
  18776. }
  18777. return this;
  18778. };
  18779. /**
  18780. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18781. * Returns the mesh.
  18782. */
  18783. AbstractMesh.prototype.updateIndices = function (indices) {
  18784. return this;
  18785. };
  18786. /**
  18787. * The mesh Geometry. Actually used by the Mesh object.
  18788. * Returns a blank geometry object.
  18789. */
  18790. /**
  18791. * Creates new normals data for the mesh.
  18792. * @param updatable.
  18793. */
  18794. AbstractMesh.prototype.createNormals = function (updatable) {
  18795. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18796. var indices = this.getIndices();
  18797. var normals;
  18798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18799. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18800. }
  18801. else {
  18802. normals = [];
  18803. }
  18804. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18805. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18806. };
  18807. /**
  18808. * Align the mesh with a normal.
  18809. * Returns the mesh.
  18810. */
  18811. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18812. if (!upDirection) {
  18813. upDirection = BABYLON.Axis.Y;
  18814. }
  18815. var axisX = BABYLON.Tmp.Vector3[0];
  18816. var axisZ = BABYLON.Tmp.Vector3[1];
  18817. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18818. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18819. if (this.rotationQuaternion) {
  18820. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18821. }
  18822. else {
  18823. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18824. }
  18825. return this;
  18826. };
  18827. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18828. var engine = this.getEngine();
  18829. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18830. this._isOccluded = false;
  18831. return;
  18832. }
  18833. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18834. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18835. if (isOcclusionQueryAvailable) {
  18836. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18837. this._isOcclusionQueryInProgress = false;
  18838. this._occlusionInternalRetryCounter = 0;
  18839. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18840. }
  18841. else {
  18842. this._occlusionInternalRetryCounter++;
  18843. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18844. this._isOcclusionQueryInProgress = false;
  18845. this._occlusionInternalRetryCounter = 0;
  18846. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18847. // if strict continue the last state of the object.
  18848. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18849. }
  18850. else {
  18851. return;
  18852. }
  18853. }
  18854. }
  18855. var scene = this.getScene();
  18856. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18857. if (!this._occlusionQuery) {
  18858. this._occlusionQuery = engine.createQuery();
  18859. }
  18860. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18861. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18862. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18863. this._isOcclusionQueryInProgress = true;
  18864. };
  18865. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18866. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18867. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18868. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18869. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18870. return AbstractMesh;
  18871. }(BABYLON.TransformNode));
  18872. BABYLON.AbstractMesh = AbstractMesh;
  18873. })(BABYLON || (BABYLON = {}));
  18874. //# sourceMappingURL=babylon.abstractMesh.js.map
  18875. var BABYLON;
  18876. (function (BABYLON) {
  18877. /**
  18878. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18879. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18880. * 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.
  18881. */
  18882. var Light = /** @class */ (function (_super) {
  18883. __extends(Light, _super);
  18884. /**
  18885. * Creates a Light object in the scene.
  18886. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18887. * @param name The firendly name of the light
  18888. * @param scene The scene the light belongs too
  18889. */
  18890. function Light(name, scene) {
  18891. var _this = _super.call(this, name, scene) || this;
  18892. /**
  18893. * Diffuse gives the basic color to an object.
  18894. */
  18895. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18896. /**
  18897. * Specular produces a highlight color on an object.
  18898. * Note: This is note affecting PBR materials.
  18899. */
  18900. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18901. /**
  18902. * Strength of the light.
  18903. * Note: By default it is define in the framework own unit.
  18904. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18905. */
  18906. _this.intensity = 1.0;
  18907. /**
  18908. * Defines how far from the source the light is impacting in scene units.
  18909. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18910. */
  18911. _this.range = Number.MAX_VALUE;
  18912. /**
  18913. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18914. * of light.
  18915. */
  18916. _this._photometricScale = 1.0;
  18917. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18918. _this._radius = 0.00001;
  18919. /**
  18920. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18921. * exceeding the number allowed of the materials.
  18922. */
  18923. _this.renderPriority = 0;
  18924. /**
  18925. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18926. * the current shadow generator.
  18927. */
  18928. _this.shadowEnabled = true;
  18929. _this._excludeWithLayerMask = 0;
  18930. _this._includeOnlyWithLayerMask = 0;
  18931. _this._lightmapMode = 0;
  18932. /**
  18933. * @ignore Internal use only.
  18934. */
  18935. _this._excludedMeshesIds = new Array();
  18936. /**
  18937. * @ignore Internal use only.
  18938. */
  18939. _this._includedOnlyMeshesIds = new Array();
  18940. _this.getScene().addLight(_this);
  18941. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18942. _this._buildUniformLayout();
  18943. _this.includedOnlyMeshes = new Array();
  18944. _this.excludedMeshes = new Array();
  18945. _this._resyncMeshes();
  18946. return _this;
  18947. }
  18948. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18949. /**
  18950. * If every light affecting the material is in this lightmapMode,
  18951. * material.lightmapTexture adds or multiplies
  18952. * (depends on material.useLightmapAsShadowmap)
  18953. * after every other light calculations.
  18954. */
  18955. get: function () {
  18956. return Light._LIGHTMAP_DEFAULT;
  18957. },
  18958. enumerable: true,
  18959. configurable: true
  18960. });
  18961. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18962. /**
  18963. * material.lightmapTexture as only diffuse lighting from this light
  18964. * adds only specular lighting from this light
  18965. * adds dynamic shadows
  18966. */
  18967. get: function () {
  18968. return Light._LIGHTMAP_SPECULAR;
  18969. },
  18970. enumerable: true,
  18971. configurable: true
  18972. });
  18973. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18974. /**
  18975. * material.lightmapTexture as only lighting
  18976. * no light calculation from this light
  18977. * only adds dynamic shadows from this light
  18978. */
  18979. get: function () {
  18980. return Light._LIGHTMAP_SHADOWSONLY;
  18981. },
  18982. enumerable: true,
  18983. configurable: true
  18984. });
  18985. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18986. /**
  18987. * Each light type uses the default quantity according to its type:
  18988. * point/spot lights use luminous intensity
  18989. * directional lights use illuminance
  18990. */
  18991. get: function () {
  18992. return Light._INTENSITYMODE_AUTOMATIC;
  18993. },
  18994. enumerable: true,
  18995. configurable: true
  18996. });
  18997. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18998. /**
  18999. * lumen (lm)
  19000. */
  19001. get: function () {
  19002. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19003. },
  19004. enumerable: true,
  19005. configurable: true
  19006. });
  19007. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19008. /**
  19009. * candela (lm/sr)
  19010. */
  19011. get: function () {
  19012. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19013. },
  19014. enumerable: true,
  19015. configurable: true
  19016. });
  19017. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19018. /**
  19019. * lux (lm/m^2)
  19020. */
  19021. get: function () {
  19022. return Light._INTENSITYMODE_ILLUMINANCE;
  19023. },
  19024. enumerable: true,
  19025. configurable: true
  19026. });
  19027. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19028. /**
  19029. * nit (cd/m^2)
  19030. */
  19031. get: function () {
  19032. return Light._INTENSITYMODE_LUMINANCE;
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19038. /**
  19039. * Light type const id of the point light.
  19040. */
  19041. get: function () {
  19042. return Light._LIGHTTYPEID_POINTLIGHT;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19048. /**
  19049. * Light type const id of the directional light.
  19050. */
  19051. get: function () {
  19052. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19058. /**
  19059. * Light type const id of the spot light.
  19060. */
  19061. get: function () {
  19062. return Light._LIGHTTYPEID_SPOTLIGHT;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19068. /**
  19069. * Light type const id of the hemispheric light.
  19070. */
  19071. get: function () {
  19072. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19073. },
  19074. enumerable: true,
  19075. configurable: true
  19076. });
  19077. Object.defineProperty(Light.prototype, "intensityMode", {
  19078. /**
  19079. * Gets the photometric scale used to interpret the intensity.
  19080. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19081. */
  19082. get: function () {
  19083. return this._intensityMode;
  19084. },
  19085. /**
  19086. * Sets the photometric scale used to interpret the intensity.
  19087. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19088. */
  19089. set: function (value) {
  19090. this._intensityMode = value;
  19091. this._computePhotometricScale();
  19092. },
  19093. enumerable: true,
  19094. configurable: true
  19095. });
  19096. ;
  19097. ;
  19098. Object.defineProperty(Light.prototype, "radius", {
  19099. /**
  19100. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19101. */
  19102. get: function () {
  19103. return this._radius;
  19104. },
  19105. /**
  19106. * sets the light radius used by PBR Materials to simulate soft area lights.
  19107. */
  19108. set: function (value) {
  19109. this._radius = value;
  19110. this._computePhotometricScale();
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. ;
  19116. ;
  19117. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19118. /**
  19119. * Gets the only meshes impacted by this light.
  19120. */
  19121. get: function () {
  19122. return this._includedOnlyMeshes;
  19123. },
  19124. /**
  19125. * Sets the only meshes impacted by this light.
  19126. */
  19127. set: function (value) {
  19128. this._includedOnlyMeshes = value;
  19129. this._hookArrayForIncludedOnly(value);
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19135. /**
  19136. * Gets the meshes not impacted by this light.
  19137. */
  19138. get: function () {
  19139. return this._excludedMeshes;
  19140. },
  19141. /**
  19142. * Sets the meshes not impacted by this light.
  19143. */
  19144. set: function (value) {
  19145. this._excludedMeshes = value;
  19146. this._hookArrayForExcluded(value);
  19147. },
  19148. enumerable: true,
  19149. configurable: true
  19150. });
  19151. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19152. /**
  19153. * Gets the layer id use to find what meshes are not impacted by the light.
  19154. * Inactive if 0
  19155. */
  19156. get: function () {
  19157. return this._excludeWithLayerMask;
  19158. },
  19159. /**
  19160. * Sets the layer id use to find what meshes are not impacted by the light.
  19161. * Inactive if 0
  19162. */
  19163. set: function (value) {
  19164. this._excludeWithLayerMask = value;
  19165. this._resyncMeshes();
  19166. },
  19167. enumerable: true,
  19168. configurable: true
  19169. });
  19170. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19171. /**
  19172. * Gets the layer id use to find what meshes are impacted by the light.
  19173. * Inactive if 0
  19174. */
  19175. get: function () {
  19176. return this._includeOnlyWithLayerMask;
  19177. },
  19178. /**
  19179. * Sets the layer id use to find what meshes are impacted by the light.
  19180. * Inactive if 0
  19181. */
  19182. set: function (value) {
  19183. this._includeOnlyWithLayerMask = value;
  19184. this._resyncMeshes();
  19185. },
  19186. enumerable: true,
  19187. configurable: true
  19188. });
  19189. Object.defineProperty(Light.prototype, "lightmapMode", {
  19190. /**
  19191. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19192. */
  19193. get: function () {
  19194. return this._lightmapMode;
  19195. },
  19196. /**
  19197. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19198. */
  19199. set: function (value) {
  19200. if (this._lightmapMode === value) {
  19201. return;
  19202. }
  19203. this._lightmapMode = value;
  19204. this._markMeshesAsLightDirty();
  19205. },
  19206. enumerable: true,
  19207. configurable: true
  19208. });
  19209. /**
  19210. * Returns the string "Light".
  19211. * @returns the class name
  19212. */
  19213. Light.prototype.getClassName = function () {
  19214. return "Light";
  19215. };
  19216. /**
  19217. * Converts the light information to a readable string for debug purpose.
  19218. * @param fullDetails Supports for multiple levels of logging within scene loading
  19219. * @returns the human readable light info
  19220. */
  19221. Light.prototype.toString = function (fullDetails) {
  19222. var ret = "Name: " + this.name;
  19223. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19224. if (this.animations) {
  19225. for (var i = 0; i < this.animations.length; i++) {
  19226. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19227. }
  19228. }
  19229. if (fullDetails) {
  19230. }
  19231. return ret;
  19232. };
  19233. /**
  19234. * Set the enabled state of this node.
  19235. * @param value - the new enabled state
  19236. * @see isEnabled
  19237. */
  19238. Light.prototype.setEnabled = function (value) {
  19239. _super.prototype.setEnabled.call(this, value);
  19240. this._resyncMeshes();
  19241. };
  19242. /**
  19243. * Returns the Light associated shadow generator if any.
  19244. * @return the associated shadow generator.
  19245. */
  19246. Light.prototype.getShadowGenerator = function () {
  19247. return this._shadowGenerator;
  19248. };
  19249. /**
  19250. * Returns a Vector3, the absolute light position in the World.
  19251. * @returns the world space position of the light
  19252. */
  19253. Light.prototype.getAbsolutePosition = function () {
  19254. return BABYLON.Vector3.Zero();
  19255. };
  19256. /**
  19257. * Specifies if the light will affect the passed mesh.
  19258. * @param mesh The mesh to test against the light
  19259. * @return true the mesh is affected otherwise, false.
  19260. */
  19261. Light.prototype.canAffectMesh = function (mesh) {
  19262. if (!mesh) {
  19263. return true;
  19264. }
  19265. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19266. return false;
  19267. }
  19268. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19269. return false;
  19270. }
  19271. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19272. return false;
  19273. }
  19274. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19275. return false;
  19276. }
  19277. return true;
  19278. };
  19279. /**
  19280. * Computes and Returns the light World matrix.
  19281. * @returns the world matrix
  19282. */
  19283. Light.prototype.getWorldMatrix = function () {
  19284. this._currentRenderId = this.getScene().getRenderId();
  19285. var worldMatrix = this._getWorldMatrix();
  19286. if (this.parent && this.parent.getWorldMatrix) {
  19287. if (!this._parentedWorldMatrix) {
  19288. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19289. }
  19290. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19291. this._markSyncedWithParent();
  19292. return this._parentedWorldMatrix;
  19293. }
  19294. return worldMatrix;
  19295. };
  19296. /**
  19297. * Sort function to order lights for rendering.
  19298. * @param a First Light object to compare to second.
  19299. * @param b Second Light object to compare first.
  19300. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19301. */
  19302. Light.CompareLightsPriority = function (a, b) {
  19303. //shadow-casting lights have priority over non-shadow-casting lights
  19304. //the renderPrioirty is a secondary sort criterion
  19305. if (a.shadowEnabled !== b.shadowEnabled) {
  19306. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19307. }
  19308. return b.renderPriority - a.renderPriority;
  19309. };
  19310. /**
  19311. * Disposes the light.
  19312. */
  19313. Light.prototype.dispose = function () {
  19314. if (this._shadowGenerator) {
  19315. this._shadowGenerator.dispose();
  19316. this._shadowGenerator = null;
  19317. }
  19318. // Animations
  19319. this.getScene().stopAnimation(this);
  19320. // Remove from meshes
  19321. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19322. var mesh = _a[_i];
  19323. mesh._removeLightSource(this);
  19324. }
  19325. this._uniformBuffer.dispose();
  19326. // Remove from scene
  19327. this.getScene().removeLight(this);
  19328. _super.prototype.dispose.call(this);
  19329. };
  19330. /**
  19331. * Returns the light type ID (integer).
  19332. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19333. */
  19334. Light.prototype.getTypeID = function () {
  19335. return 0;
  19336. };
  19337. /**
  19338. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19339. * @returns the scaled intensity in intensity mode unit
  19340. */
  19341. Light.prototype.getScaledIntensity = function () {
  19342. return this._photometricScale * this.intensity;
  19343. };
  19344. /**
  19345. * Returns a new Light object, named "name", from the current one.
  19346. * @param name The name of the cloned light
  19347. * @returns the new created light
  19348. */
  19349. Light.prototype.clone = function (name) {
  19350. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19351. if (!constructor) {
  19352. return null;
  19353. }
  19354. return BABYLON.SerializationHelper.Clone(constructor, this);
  19355. };
  19356. /**
  19357. * Serializes the current light into a Serialization object.
  19358. * @returns the serialized object.
  19359. */
  19360. Light.prototype.serialize = function () {
  19361. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19362. // Type
  19363. serializationObject.type = this.getTypeID();
  19364. // Parent
  19365. if (this.parent) {
  19366. serializationObject.parentId = this.parent.id;
  19367. }
  19368. // Inclusion / exclusions
  19369. if (this.excludedMeshes.length > 0) {
  19370. serializationObject.excludedMeshesIds = [];
  19371. this.excludedMeshes.forEach(function (mesh) {
  19372. serializationObject.excludedMeshesIds.push(mesh.id);
  19373. });
  19374. }
  19375. if (this.includedOnlyMeshes.length > 0) {
  19376. serializationObject.includedOnlyMeshesIds = [];
  19377. this.includedOnlyMeshes.forEach(function (mesh) {
  19378. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19379. });
  19380. }
  19381. // Animations
  19382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19383. serializationObject.ranges = this.serializeAnimationRanges();
  19384. return serializationObject;
  19385. };
  19386. /**
  19387. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19388. * This new light is named "name" and added to the passed scene.
  19389. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19390. * @param name The friendly name of the light
  19391. * @param scene The scene the new light will belong to
  19392. * @returns the constructor function
  19393. */
  19394. Light.GetConstructorFromName = function (type, name, scene) {
  19395. switch (type) {
  19396. case 0:
  19397. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19398. case 1:
  19399. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19400. case 2:
  19401. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19402. case 3:
  19403. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19404. }
  19405. return null;
  19406. };
  19407. /**
  19408. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19409. * @param parsedLight The JSON representation of the light
  19410. * @param scene The scene to create the parsed light in
  19411. * @returns the created light after parsing
  19412. */
  19413. Light.Parse = function (parsedLight, scene) {
  19414. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19415. if (!constructor) {
  19416. return null;
  19417. }
  19418. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19419. // Inclusion / exclusions
  19420. if (parsedLight.excludedMeshesIds) {
  19421. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19422. }
  19423. if (parsedLight.includedOnlyMeshesIds) {
  19424. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19425. }
  19426. // Parent
  19427. if (parsedLight.parentId) {
  19428. light._waitingParentId = parsedLight.parentId;
  19429. }
  19430. // Animations
  19431. if (parsedLight.animations) {
  19432. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19433. var parsedAnimation = parsedLight.animations[animationIndex];
  19434. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19435. }
  19436. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19437. }
  19438. if (parsedLight.autoAnimate) {
  19439. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19440. }
  19441. return light;
  19442. };
  19443. Light.prototype._hookArrayForExcluded = function (array) {
  19444. var _this = this;
  19445. var oldPush = array.push;
  19446. array.push = function () {
  19447. var items = [];
  19448. for (var _i = 0; _i < arguments.length; _i++) {
  19449. items[_i] = arguments[_i];
  19450. }
  19451. var result = oldPush.apply(array, items);
  19452. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19453. var item = items_1[_a];
  19454. item._resyncLighSource(_this);
  19455. }
  19456. return result;
  19457. };
  19458. var oldSplice = array.splice;
  19459. array.splice = function (index, deleteCount) {
  19460. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19461. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19462. var item = deleted_1[_i];
  19463. item._resyncLighSource(_this);
  19464. }
  19465. return deleted;
  19466. };
  19467. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19468. var item = array_1[_i];
  19469. item._resyncLighSource(this);
  19470. }
  19471. };
  19472. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19473. var _this = this;
  19474. var oldPush = array.push;
  19475. array.push = function () {
  19476. var items = [];
  19477. for (var _i = 0; _i < arguments.length; _i++) {
  19478. items[_i] = arguments[_i];
  19479. }
  19480. var result = oldPush.apply(array, items);
  19481. _this._resyncMeshes();
  19482. return result;
  19483. };
  19484. var oldSplice = array.splice;
  19485. array.splice = function (index, deleteCount) {
  19486. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19487. _this._resyncMeshes();
  19488. return deleted;
  19489. };
  19490. this._resyncMeshes();
  19491. };
  19492. Light.prototype._resyncMeshes = function () {
  19493. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19494. var mesh = _a[_i];
  19495. mesh._resyncLighSource(this);
  19496. }
  19497. };
  19498. /**
  19499. * Forces the meshes to update their light related information in their rendering used effects
  19500. * @ignore Internal Use Only
  19501. */
  19502. Light.prototype._markMeshesAsLightDirty = function () {
  19503. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19504. var mesh = _a[_i];
  19505. if (mesh._lightSources.indexOf(this) !== -1) {
  19506. mesh._markSubMeshesAsLightDirty();
  19507. }
  19508. }
  19509. };
  19510. /**
  19511. * Recomputes the cached photometric scale if needed.
  19512. */
  19513. Light.prototype._computePhotometricScale = function () {
  19514. this._photometricScale = this._getPhotometricScale();
  19515. this.getScene().resetCachedMaterial();
  19516. };
  19517. /**
  19518. * Returns the Photometric Scale according to the light type and intensity mode.
  19519. */
  19520. Light.prototype._getPhotometricScale = function () {
  19521. var photometricScale = 0.0;
  19522. var lightTypeID = this.getTypeID();
  19523. //get photometric mode
  19524. var photometricMode = this.intensityMode;
  19525. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19526. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19527. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19528. }
  19529. else {
  19530. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19531. }
  19532. }
  19533. //compute photometric scale
  19534. switch (lightTypeID) {
  19535. case Light.LIGHTTYPEID_POINTLIGHT:
  19536. case Light.LIGHTTYPEID_SPOTLIGHT:
  19537. switch (photometricMode) {
  19538. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19539. photometricScale = 1.0 / (4.0 * Math.PI);
  19540. break;
  19541. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19542. photometricScale = 1.0;
  19543. break;
  19544. case Light.INTENSITYMODE_LUMINANCE:
  19545. photometricScale = this.radius * this.radius;
  19546. break;
  19547. }
  19548. break;
  19549. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19550. switch (photometricMode) {
  19551. case Light.INTENSITYMODE_ILLUMINANCE:
  19552. photometricScale = 1.0;
  19553. break;
  19554. case Light.INTENSITYMODE_LUMINANCE:
  19555. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19556. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19557. var apexAngleRadians = this.radius;
  19558. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19559. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19560. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19561. photometricScale = solidAngle;
  19562. break;
  19563. }
  19564. break;
  19565. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19566. // No fall off in hemisperic light.
  19567. photometricScale = 1.0;
  19568. break;
  19569. }
  19570. return photometricScale;
  19571. };
  19572. /**
  19573. * Reorder the light in the scene according to their defined priority.
  19574. * @ignore Internal Use Only
  19575. */
  19576. Light.prototype._reorderLightsInScene = function () {
  19577. var scene = this.getScene();
  19578. if (this._renderPriority != 0) {
  19579. scene.requireLightSorting = true;
  19580. }
  19581. this.getScene().sortLightsByPriority();
  19582. };
  19583. //lightmapMode Consts
  19584. Light._LIGHTMAP_DEFAULT = 0;
  19585. Light._LIGHTMAP_SPECULAR = 1;
  19586. Light._LIGHTMAP_SHADOWSONLY = 2;
  19587. // Intensity Mode Consts
  19588. Light._INTENSITYMODE_AUTOMATIC = 0;
  19589. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19590. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19591. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19592. Light._INTENSITYMODE_LUMINANCE = 4;
  19593. // Light types ids const.
  19594. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19595. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19596. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19597. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19598. __decorate([
  19599. BABYLON.serializeAsColor3()
  19600. ], Light.prototype, "diffuse", void 0);
  19601. __decorate([
  19602. BABYLON.serializeAsColor3()
  19603. ], Light.prototype, "specular", void 0);
  19604. __decorate([
  19605. BABYLON.serialize()
  19606. ], Light.prototype, "intensity", void 0);
  19607. __decorate([
  19608. BABYLON.serialize()
  19609. ], Light.prototype, "range", void 0);
  19610. __decorate([
  19611. BABYLON.serialize()
  19612. ], Light.prototype, "intensityMode", null);
  19613. __decorate([
  19614. BABYLON.serialize()
  19615. ], Light.prototype, "radius", null);
  19616. __decorate([
  19617. BABYLON.serialize()
  19618. ], Light.prototype, "_renderPriority", void 0);
  19619. __decorate([
  19620. BABYLON.expandToProperty("_reorderLightsInScene")
  19621. ], Light.prototype, "renderPriority", void 0);
  19622. __decorate([
  19623. BABYLON.serialize()
  19624. ], Light.prototype, "shadowEnabled", void 0);
  19625. __decorate([
  19626. BABYLON.serialize("excludeWithLayerMask")
  19627. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19628. __decorate([
  19629. BABYLON.serialize("includeOnlyWithLayerMask")
  19630. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19631. __decorate([
  19632. BABYLON.serialize("lightmapMode")
  19633. ], Light.prototype, "_lightmapMode", void 0);
  19634. return Light;
  19635. }(BABYLON.Node));
  19636. BABYLON.Light = Light;
  19637. })(BABYLON || (BABYLON = {}));
  19638. //# sourceMappingURL=babylon.light.js.map
  19639. var BABYLON;
  19640. (function (BABYLON) {
  19641. var Camera = /** @class */ (function (_super) {
  19642. __extends(Camera, _super);
  19643. function Camera(name, position, scene) {
  19644. var _this = _super.call(this, name, scene) || this;
  19645. /**
  19646. * The vector the camera should consider as up.
  19647. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19648. */
  19649. _this.upVector = BABYLON.Vector3.Up();
  19650. _this.orthoLeft = null;
  19651. _this.orthoRight = null;
  19652. _this.orthoBottom = null;
  19653. _this.orthoTop = null;
  19654. /**
  19655. * FOV is set in Radians. (default is 0.8)
  19656. */
  19657. _this.fov = 0.8;
  19658. _this.minZ = 1;
  19659. _this.maxZ = 10000.0;
  19660. _this.inertia = 0.9;
  19661. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19662. _this.isIntermediate = false;
  19663. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19664. /**
  19665. * Restricts the camera to viewing objects with the same layerMask.
  19666. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19667. */
  19668. _this.layerMask = 0x0FFFFFFF;
  19669. /**
  19670. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19671. */
  19672. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19673. // Camera rig members
  19674. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19675. _this._rigCameras = new Array();
  19676. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19677. _this._skipRendering = false;
  19678. _this.customRenderTargets = new Array();
  19679. // Observables
  19680. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19681. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19682. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19683. _this.onRestoreStateObservable = new BABYLON.Observable();
  19684. // Cache
  19685. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19686. _this._projectionMatrix = new BABYLON.Matrix();
  19687. _this._doNotComputeProjectionMatrix = false;
  19688. _this._postProcesses = new Array();
  19689. _this._transformMatrix = BABYLON.Matrix.Zero();
  19690. _this._activeMeshes = new BABYLON.SmartArray(256);
  19691. _this._globalPosition = BABYLON.Vector3.Zero();
  19692. _this._refreshFrustumPlanes = true;
  19693. _this.getScene().addCamera(_this);
  19694. if (!_this.getScene().activeCamera) {
  19695. _this.getScene().activeCamera = _this;
  19696. }
  19697. _this.position = position;
  19698. return _this;
  19699. }
  19700. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19701. get: function () {
  19702. return Camera._PERSPECTIVE_CAMERA;
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19708. get: function () {
  19709. return Camera._ORTHOGRAPHIC_CAMERA;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19715. /**
  19716. * This is the default FOV mode for perspective cameras.
  19717. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19718. *
  19719. */
  19720. get: function () {
  19721. return Camera._FOVMODE_VERTICAL_FIXED;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19727. /**
  19728. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19729. *
  19730. */
  19731. get: function () {
  19732. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19738. get: function () {
  19739. return Camera._RIG_MODE_NONE;
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19745. get: function () {
  19746. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19752. get: function () {
  19753. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19759. get: function () {
  19760. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19766. get: function () {
  19767. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19773. get: function () {
  19774. return Camera._RIG_MODE_VR;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19780. get: function () {
  19781. return Camera._RIG_MODE_WEBVR;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. /**
  19787. * Store current camera state (fov, position, etc..)
  19788. */
  19789. Camera.prototype.storeState = function () {
  19790. this._stateStored = true;
  19791. this._storedFov = this.fov;
  19792. return this;
  19793. };
  19794. /**
  19795. * Restores the camera state values if it has been stored. You must call storeState() first
  19796. */
  19797. Camera.prototype._restoreStateValues = function () {
  19798. if (!this._stateStored) {
  19799. return false;
  19800. }
  19801. this.fov = this._storedFov;
  19802. return true;
  19803. };
  19804. /**
  19805. * Restored camera state. You must call storeState() first
  19806. */
  19807. Camera.prototype.restoreState = function () {
  19808. if (this._restoreStateValues()) {
  19809. this.onRestoreStateObservable.notifyObservers(this);
  19810. return true;
  19811. }
  19812. return false;
  19813. };
  19814. Camera.prototype.getClassName = function () {
  19815. return "Camera";
  19816. };
  19817. /**
  19818. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19819. */
  19820. Camera.prototype.toString = function (fullDetails) {
  19821. var ret = "Name: " + this.name;
  19822. ret += ", type: " + this.getClassName();
  19823. if (this.animations) {
  19824. for (var i = 0; i < this.animations.length; i++) {
  19825. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19826. }
  19827. }
  19828. if (fullDetails) {
  19829. }
  19830. return ret;
  19831. };
  19832. Object.defineProperty(Camera.prototype, "globalPosition", {
  19833. get: function () {
  19834. return this._globalPosition;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Camera.prototype.getActiveMeshes = function () {
  19840. return this._activeMeshes;
  19841. };
  19842. Camera.prototype.isActiveMesh = function (mesh) {
  19843. return (this._activeMeshes.indexOf(mesh) !== -1);
  19844. };
  19845. //Cache
  19846. Camera.prototype._initCache = function () {
  19847. _super.prototype._initCache.call(this);
  19848. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19849. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19850. this._cache.mode = undefined;
  19851. this._cache.minZ = undefined;
  19852. this._cache.maxZ = undefined;
  19853. this._cache.fov = undefined;
  19854. this._cache.fovMode = undefined;
  19855. this._cache.aspectRatio = undefined;
  19856. this._cache.orthoLeft = undefined;
  19857. this._cache.orthoRight = undefined;
  19858. this._cache.orthoBottom = undefined;
  19859. this._cache.orthoTop = undefined;
  19860. this._cache.renderWidth = undefined;
  19861. this._cache.renderHeight = undefined;
  19862. };
  19863. Camera.prototype._updateCache = function (ignoreParentClass) {
  19864. if (!ignoreParentClass) {
  19865. _super.prototype._updateCache.call(this);
  19866. }
  19867. this._cache.position.copyFrom(this.position);
  19868. this._cache.upVector.copyFrom(this.upVector);
  19869. };
  19870. // Synchronized
  19871. Camera.prototype._isSynchronized = function () {
  19872. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19873. };
  19874. Camera.prototype._isSynchronizedViewMatrix = function () {
  19875. if (!_super.prototype._isSynchronized.call(this))
  19876. return false;
  19877. return this._cache.position.equals(this.position)
  19878. && this._cache.upVector.equals(this.upVector)
  19879. && this.isSynchronizedWithParent();
  19880. };
  19881. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19882. var check = this._cache.mode === this.mode
  19883. && this._cache.minZ === this.minZ
  19884. && this._cache.maxZ === this.maxZ;
  19885. if (!check) {
  19886. return false;
  19887. }
  19888. var engine = this.getEngine();
  19889. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19890. check = this._cache.fov === this.fov
  19891. && this._cache.fovMode === this.fovMode
  19892. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19893. }
  19894. else {
  19895. check = this._cache.orthoLeft === this.orthoLeft
  19896. && this._cache.orthoRight === this.orthoRight
  19897. && this._cache.orthoBottom === this.orthoBottom
  19898. && this._cache.orthoTop === this.orthoTop
  19899. && this._cache.renderWidth === engine.getRenderWidth()
  19900. && this._cache.renderHeight === engine.getRenderHeight();
  19901. }
  19902. return check;
  19903. };
  19904. // Controls
  19905. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19906. };
  19907. Camera.prototype.detachControl = function (element) {
  19908. };
  19909. Camera.prototype.update = function () {
  19910. this._checkInputs();
  19911. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19912. this._updateRigCameras();
  19913. }
  19914. };
  19915. Camera.prototype._checkInputs = function () {
  19916. this.onAfterCheckInputsObservable.notifyObservers(this);
  19917. };
  19918. Object.defineProperty(Camera.prototype, "rigCameras", {
  19919. get: function () {
  19920. return this._rigCameras;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19926. get: function () {
  19927. return this._rigPostProcess;
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19933. // invalidate framebuffer
  19934. if (this._postProcesses.length > 0) {
  19935. this._postProcesses[0].markTextureDirty();
  19936. }
  19937. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19938. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19939. var cam = this._rigCameras[i];
  19940. var rigPostProcess = cam._rigPostProcess;
  19941. // for VR rig, there does not have to be a post process
  19942. if (rigPostProcess) {
  19943. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19944. if (isPass) {
  19945. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19946. cam.isIntermediate = this._postProcesses.length === 0;
  19947. }
  19948. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19949. rigPostProcess.markTextureDirty();
  19950. }
  19951. else {
  19952. cam._postProcesses = this._postProcesses.slice(0);
  19953. }
  19954. }
  19955. };
  19956. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19957. if (insertAt === void 0) { insertAt = null; }
  19958. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19959. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19960. return 0;
  19961. }
  19962. if (insertAt == null || insertAt < 0) {
  19963. this._postProcesses.push(postProcess);
  19964. }
  19965. else {
  19966. this._postProcesses.splice(insertAt, 0, postProcess);
  19967. }
  19968. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19969. return this._postProcesses.indexOf(postProcess);
  19970. };
  19971. Camera.prototype.detachPostProcess = function (postProcess) {
  19972. var idx = this._postProcesses.indexOf(postProcess);
  19973. if (idx !== -1) {
  19974. this._postProcesses.splice(idx, 1);
  19975. }
  19976. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19977. };
  19978. Camera.prototype.getWorldMatrix = function () {
  19979. if (!this._worldMatrix) {
  19980. this._worldMatrix = BABYLON.Matrix.Identity();
  19981. }
  19982. var viewMatrix = this.getViewMatrix();
  19983. viewMatrix.invertToRef(this._worldMatrix);
  19984. return this._worldMatrix;
  19985. };
  19986. Camera.prototype._getViewMatrix = function () {
  19987. return BABYLON.Matrix.Identity();
  19988. };
  19989. Camera.prototype.getViewMatrix = function (force) {
  19990. if (!force && this._isSynchronizedViewMatrix()) {
  19991. return this._computedViewMatrix;
  19992. }
  19993. this.updateCache();
  19994. this._computedViewMatrix = this._getViewMatrix();
  19995. this._currentRenderId = this.getScene().getRenderId();
  19996. this._refreshFrustumPlanes = true;
  19997. if (!this.parent || !this.parent.getWorldMatrix) {
  19998. this._globalPosition.copyFrom(this.position);
  19999. }
  20000. else {
  20001. if (!this._worldMatrix) {
  20002. this._worldMatrix = BABYLON.Matrix.Identity();
  20003. }
  20004. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20005. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20006. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20007. this._computedViewMatrix.invert();
  20008. this._markSyncedWithParent();
  20009. }
  20010. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20011. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20012. }
  20013. this.onViewMatrixChangedObservable.notifyObservers(this);
  20014. return this._computedViewMatrix;
  20015. };
  20016. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20017. this._doNotComputeProjectionMatrix = true;
  20018. if (projection !== undefined) {
  20019. this._projectionMatrix = projection;
  20020. }
  20021. };
  20022. ;
  20023. Camera.prototype.unfreezeProjectionMatrix = function () {
  20024. this._doNotComputeProjectionMatrix = false;
  20025. };
  20026. ;
  20027. Camera.prototype.getProjectionMatrix = function (force) {
  20028. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20029. return this._projectionMatrix;
  20030. }
  20031. // Cache
  20032. this._cache.mode = this.mode;
  20033. this._cache.minZ = this.minZ;
  20034. this._cache.maxZ = this.maxZ;
  20035. // Matrix
  20036. this._refreshFrustumPlanes = true;
  20037. var engine = this.getEngine();
  20038. var scene = this.getScene();
  20039. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20040. this._cache.fov = this.fov;
  20041. this._cache.fovMode = this.fovMode;
  20042. this._cache.aspectRatio = engine.getAspectRatio(this);
  20043. if (this.minZ <= 0) {
  20044. this.minZ = 0.1;
  20045. }
  20046. if (scene.useRightHandedSystem) {
  20047. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20048. }
  20049. else {
  20050. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20051. }
  20052. }
  20053. else {
  20054. var halfWidth = engine.getRenderWidth() / 2.0;
  20055. var halfHeight = engine.getRenderHeight() / 2.0;
  20056. if (scene.useRightHandedSystem) {
  20057. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20058. }
  20059. else {
  20060. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20061. }
  20062. this._cache.orthoLeft = this.orthoLeft;
  20063. this._cache.orthoRight = this.orthoRight;
  20064. this._cache.orthoBottom = this.orthoBottom;
  20065. this._cache.orthoTop = this.orthoTop;
  20066. this._cache.renderWidth = engine.getRenderWidth();
  20067. this._cache.renderHeight = engine.getRenderHeight();
  20068. }
  20069. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20070. return this._projectionMatrix;
  20071. };
  20072. Camera.prototype.getTranformationMatrix = function () {
  20073. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20074. return this._transformMatrix;
  20075. };
  20076. Camera.prototype.updateFrustumPlanes = function () {
  20077. if (!this._refreshFrustumPlanes) {
  20078. return;
  20079. }
  20080. this.getTranformationMatrix();
  20081. if (!this._frustumPlanes) {
  20082. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20083. }
  20084. else {
  20085. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20086. }
  20087. this._refreshFrustumPlanes = false;
  20088. };
  20089. Camera.prototype.isInFrustum = function (target) {
  20090. this.updateFrustumPlanes();
  20091. return target.isInFrustum(this._frustumPlanes);
  20092. };
  20093. Camera.prototype.isCompletelyInFrustum = function (target) {
  20094. this.updateFrustumPlanes();
  20095. return target.isCompletelyInFrustum(this._frustumPlanes);
  20096. };
  20097. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20098. if (length === void 0) { length = 100; }
  20099. if (!transform) {
  20100. transform = this.getWorldMatrix();
  20101. }
  20102. if (!origin) {
  20103. origin = this.position;
  20104. }
  20105. var forward = new BABYLON.Vector3(0, 0, 1);
  20106. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20107. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20108. return new BABYLON.Ray(origin, direction, length);
  20109. };
  20110. Camera.prototype.dispose = function () {
  20111. // Observables
  20112. this.onViewMatrixChangedObservable.clear();
  20113. this.onProjectionMatrixChangedObservable.clear();
  20114. this.onAfterCheckInputsObservable.clear();
  20115. this.onRestoreStateObservable.clear();
  20116. // Inputs
  20117. if (this.inputs) {
  20118. this.inputs.clear();
  20119. }
  20120. // Animations
  20121. this.getScene().stopAnimation(this);
  20122. // Remove from scene
  20123. this.getScene().removeCamera(this);
  20124. while (this._rigCameras.length > 0) {
  20125. var camera = this._rigCameras.pop();
  20126. if (camera) {
  20127. camera.dispose();
  20128. }
  20129. }
  20130. // Postprocesses
  20131. if (this._rigPostProcess) {
  20132. this._rigPostProcess.dispose(this);
  20133. this._rigPostProcess = null;
  20134. this._postProcesses = [];
  20135. }
  20136. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20137. this._rigPostProcess = null;
  20138. this._postProcesses = [];
  20139. }
  20140. else {
  20141. var i = this._postProcesses.length;
  20142. while (--i >= 0) {
  20143. this._postProcesses[i].dispose(this);
  20144. }
  20145. }
  20146. // Render targets
  20147. var i = this.customRenderTargets.length;
  20148. while (--i >= 0) {
  20149. this.customRenderTargets[i].dispose();
  20150. }
  20151. this.customRenderTargets = [];
  20152. // Active Meshes
  20153. this._activeMeshes.dispose();
  20154. _super.prototype.dispose.call(this);
  20155. };
  20156. Object.defineProperty(Camera.prototype, "leftCamera", {
  20157. // ---- Camera rigs section ----
  20158. get: function () {
  20159. if (this._rigCameras.length < 1) {
  20160. return null;
  20161. }
  20162. return this._rigCameras[0];
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. Object.defineProperty(Camera.prototype, "rightCamera", {
  20168. get: function () {
  20169. if (this._rigCameras.length < 2) {
  20170. return null;
  20171. }
  20172. return this._rigCameras[1];
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Camera.prototype.getLeftTarget = function () {
  20178. if (this._rigCameras.length < 1) {
  20179. return null;
  20180. }
  20181. return this._rigCameras[0].getTarget();
  20182. };
  20183. Camera.prototype.getRightTarget = function () {
  20184. if (this._rigCameras.length < 2) {
  20185. return null;
  20186. }
  20187. return this._rigCameras[1].getTarget();
  20188. };
  20189. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20190. if (this.cameraRigMode === mode) {
  20191. return;
  20192. }
  20193. while (this._rigCameras.length > 0) {
  20194. var camera = this._rigCameras.pop();
  20195. if (camera) {
  20196. camera.dispose();
  20197. }
  20198. }
  20199. this.cameraRigMode = mode;
  20200. this._cameraRigParams = {};
  20201. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20202. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20203. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20204. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20205. // create the rig cameras, unless none
  20206. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20207. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20208. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20209. if (leftCamera && rightCamera) {
  20210. this._rigCameras.push(leftCamera);
  20211. this._rigCameras.push(rightCamera);
  20212. }
  20213. }
  20214. switch (this.cameraRigMode) {
  20215. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20216. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20217. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20218. break;
  20219. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20220. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20221. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20222. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20223. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20224. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20225. break;
  20226. case Camera.RIG_MODE_VR:
  20227. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20228. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20229. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20230. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20231. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20232. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20233. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20234. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20235. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20236. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20237. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20238. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20239. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20240. if (metrics.compensateDistortion) {
  20241. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20242. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20243. }
  20244. break;
  20245. case Camera.RIG_MODE_WEBVR:
  20246. if (rigParams.vrDisplay) {
  20247. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20248. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20249. //Left eye
  20250. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20251. this._rigCameras[0].setCameraRigParameter("left", true);
  20252. //leaving this for future reference
  20253. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20254. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20255. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20256. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20257. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20258. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20259. this._rigCameras[0].parent = this;
  20260. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20261. //Right eye
  20262. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20263. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20264. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20265. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20266. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20267. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20268. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20269. this._rigCameras[1].parent = this;
  20270. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20271. if (Camera.UseAlternateWebVRRendering) {
  20272. this._rigCameras[1]._skipRendering = true;
  20273. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20274. }
  20275. }
  20276. break;
  20277. }
  20278. this._cascadePostProcessesToRigCams();
  20279. this.update();
  20280. };
  20281. Camera.prototype._getVRProjectionMatrix = function () {
  20282. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20283. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20284. return this._projectionMatrix;
  20285. };
  20286. Camera.prototype._updateCameraRotationMatrix = function () {
  20287. //Here for WebVR
  20288. };
  20289. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20290. //Here for WebVR
  20291. };
  20292. /**
  20293. * This function MUST be overwritten by the different WebVR cameras available.
  20294. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20295. */
  20296. Camera.prototype._getWebVRProjectionMatrix = function () {
  20297. return BABYLON.Matrix.Identity();
  20298. };
  20299. /**
  20300. * This function MUST be overwritten by the different WebVR cameras available.
  20301. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20302. */
  20303. Camera.prototype._getWebVRViewMatrix = function () {
  20304. return BABYLON.Matrix.Identity();
  20305. };
  20306. Camera.prototype.setCameraRigParameter = function (name, value) {
  20307. if (!this._cameraRigParams) {
  20308. this._cameraRigParams = {};
  20309. }
  20310. this._cameraRigParams[name] = value;
  20311. //provisionnally:
  20312. if (name === "interaxialDistance") {
  20313. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20314. }
  20315. };
  20316. /**
  20317. * needs to be overridden by children so sub has required properties to be copied
  20318. */
  20319. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20320. return null;
  20321. };
  20322. /**
  20323. * May need to be overridden by children
  20324. */
  20325. Camera.prototype._updateRigCameras = function () {
  20326. for (var i = 0; i < this._rigCameras.length; i++) {
  20327. this._rigCameras[i].minZ = this.minZ;
  20328. this._rigCameras[i].maxZ = this.maxZ;
  20329. this._rigCameras[i].fov = this.fov;
  20330. }
  20331. // only update viewport when ANAGLYPH
  20332. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20333. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20334. }
  20335. };
  20336. Camera.prototype._setupInputs = function () {
  20337. };
  20338. Camera.prototype.serialize = function () {
  20339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20340. // Type
  20341. serializationObject.type = this.getClassName();
  20342. // Parent
  20343. if (this.parent) {
  20344. serializationObject.parentId = this.parent.id;
  20345. }
  20346. if (this.inputs) {
  20347. this.inputs.serialize(serializationObject);
  20348. }
  20349. // Animations
  20350. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20351. serializationObject.ranges = this.serializeAnimationRanges();
  20352. return serializationObject;
  20353. };
  20354. Camera.prototype.clone = function (name) {
  20355. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20356. };
  20357. Camera.prototype.getDirection = function (localAxis) {
  20358. var result = BABYLON.Vector3.Zero();
  20359. this.getDirectionToRef(localAxis, result);
  20360. return result;
  20361. };
  20362. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20363. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20364. };
  20365. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20366. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20367. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20368. switch (type) {
  20369. case "ArcRotateCamera":
  20370. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20371. case "DeviceOrientationCamera":
  20372. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20373. case "FollowCamera":
  20374. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20375. case "ArcFollowCamera":
  20376. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20377. case "GamepadCamera":
  20378. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20379. case "TouchCamera":
  20380. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20381. case "VirtualJoysticksCamera":
  20382. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20383. case "WebVRFreeCamera":
  20384. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20385. case "WebVRGamepadCamera":
  20386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20387. case "VRDeviceOrientationFreeCamera":
  20388. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20389. case "VRDeviceOrientationGamepadCamera":
  20390. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20391. case "AnaglyphArcRotateCamera":
  20392. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20393. case "AnaglyphFreeCamera":
  20394. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20395. case "AnaglyphGamepadCamera":
  20396. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20397. case "AnaglyphUniversalCamera":
  20398. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20399. case "StereoscopicArcRotateCamera":
  20400. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20401. case "StereoscopicFreeCamera":
  20402. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20403. case "StereoscopicGamepadCamera":
  20404. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20405. case "StereoscopicUniversalCamera":
  20406. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20407. case "FreeCamera":// Forcing Universal here
  20408. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20409. default:// Universal Camera is the default value
  20410. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20411. }
  20412. };
  20413. Camera.prototype.computeWorldMatrix = function () {
  20414. return this.getWorldMatrix();
  20415. };
  20416. Camera.Parse = function (parsedCamera, scene) {
  20417. var type = parsedCamera.type;
  20418. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20419. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20420. // Parent
  20421. if (parsedCamera.parentId) {
  20422. camera._waitingParentId = parsedCamera.parentId;
  20423. }
  20424. //If camera has an input manager, let it parse inputs settings
  20425. if (camera.inputs) {
  20426. camera.inputs.parse(parsedCamera);
  20427. camera._setupInputs();
  20428. }
  20429. if (camera.setPosition) {
  20430. camera.position.copyFromFloats(0, 0, 0);
  20431. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20432. }
  20433. // Target
  20434. if (parsedCamera.target) {
  20435. if (camera.setTarget) {
  20436. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20437. }
  20438. }
  20439. // Apply 3d rig, when found
  20440. if (parsedCamera.cameraRigMode) {
  20441. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20442. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20443. }
  20444. // Animations
  20445. if (parsedCamera.animations) {
  20446. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20447. var parsedAnimation = parsedCamera.animations[animationIndex];
  20448. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20449. }
  20450. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20451. }
  20452. if (parsedCamera.autoAnimate) {
  20453. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20454. }
  20455. return camera;
  20456. };
  20457. // Statics
  20458. Camera._PERSPECTIVE_CAMERA = 0;
  20459. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20460. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20461. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20462. Camera._RIG_MODE_NONE = 0;
  20463. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20464. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20465. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20466. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20467. Camera._RIG_MODE_VR = 20;
  20468. Camera._RIG_MODE_WEBVR = 21;
  20469. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20470. Camera.UseAlternateWebVRRendering = false;
  20471. __decorate([
  20472. BABYLON.serializeAsVector3()
  20473. ], Camera.prototype, "position", void 0);
  20474. __decorate([
  20475. BABYLON.serializeAsVector3()
  20476. ], Camera.prototype, "upVector", void 0);
  20477. __decorate([
  20478. BABYLON.serialize()
  20479. ], Camera.prototype, "orthoLeft", void 0);
  20480. __decorate([
  20481. BABYLON.serialize()
  20482. ], Camera.prototype, "orthoRight", void 0);
  20483. __decorate([
  20484. BABYLON.serialize()
  20485. ], Camera.prototype, "orthoBottom", void 0);
  20486. __decorate([
  20487. BABYLON.serialize()
  20488. ], Camera.prototype, "orthoTop", void 0);
  20489. __decorate([
  20490. BABYLON.serialize()
  20491. ], Camera.prototype, "fov", void 0);
  20492. __decorate([
  20493. BABYLON.serialize()
  20494. ], Camera.prototype, "minZ", void 0);
  20495. __decorate([
  20496. BABYLON.serialize()
  20497. ], Camera.prototype, "maxZ", void 0);
  20498. __decorate([
  20499. BABYLON.serialize()
  20500. ], Camera.prototype, "inertia", void 0);
  20501. __decorate([
  20502. BABYLON.serialize()
  20503. ], Camera.prototype, "mode", void 0);
  20504. __decorate([
  20505. BABYLON.serialize()
  20506. ], Camera.prototype, "layerMask", void 0);
  20507. __decorate([
  20508. BABYLON.serialize()
  20509. ], Camera.prototype, "fovMode", void 0);
  20510. __decorate([
  20511. BABYLON.serialize()
  20512. ], Camera.prototype, "cameraRigMode", void 0);
  20513. __decorate([
  20514. BABYLON.serialize()
  20515. ], Camera.prototype, "interaxialDistance", void 0);
  20516. __decorate([
  20517. BABYLON.serialize()
  20518. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20519. return Camera;
  20520. }(BABYLON.Node));
  20521. BABYLON.Camera = Camera;
  20522. })(BABYLON || (BABYLON = {}));
  20523. //# sourceMappingURL=babylon.camera.js.map
  20524. var BABYLON;
  20525. (function (BABYLON) {
  20526. var RenderingManager = /** @class */ (function () {
  20527. function RenderingManager(scene) {
  20528. this._renderingGroups = new Array();
  20529. this._autoClearDepthStencil = {};
  20530. this._customOpaqueSortCompareFn = {};
  20531. this._customAlphaTestSortCompareFn = {};
  20532. this._customTransparentSortCompareFn = {};
  20533. this._renderinGroupInfo = null;
  20534. this._scene = scene;
  20535. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20536. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20537. }
  20538. }
  20539. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20540. if (depth === void 0) { depth = true; }
  20541. if (stencil === void 0) { stencil = true; }
  20542. if (this._depthStencilBufferAlreadyCleaned) {
  20543. return;
  20544. }
  20545. this._scene.getEngine().clear(null, false, depth, stencil);
  20546. this._depthStencilBufferAlreadyCleaned = true;
  20547. };
  20548. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20549. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20550. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20551. var info = null;
  20552. if (observable) {
  20553. if (!this._renderinGroupInfo) {
  20554. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20555. }
  20556. info = this._renderinGroupInfo;
  20557. info.scene = this._scene;
  20558. info.camera = this._scene.activeCamera;
  20559. }
  20560. // Dispatch sprites
  20561. if (renderSprites) {
  20562. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20563. var manager = this._scene.spriteManagers[index];
  20564. this.dispatchSprites(manager);
  20565. }
  20566. }
  20567. // Render
  20568. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20569. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20570. var renderingGroup = this._renderingGroups[index];
  20571. if (!renderingGroup && !observable)
  20572. continue;
  20573. var renderingGroupMask = 0;
  20574. // Fire PRECLEAR stage
  20575. if (observable && info) {
  20576. renderingGroupMask = Math.pow(2, index);
  20577. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20578. info.renderingGroupId = index;
  20579. observable.notifyObservers(info, renderingGroupMask);
  20580. }
  20581. // Clear depth/stencil if needed
  20582. if (RenderingManager.AUTOCLEAR) {
  20583. var autoClear = this._autoClearDepthStencil[index];
  20584. if (autoClear && autoClear.autoClear) {
  20585. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20586. }
  20587. }
  20588. if (observable && info) {
  20589. // Fire PREOPAQUE stage
  20590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20591. observable.notifyObservers(info, renderingGroupMask);
  20592. // Fire PRETRANSPARENT stage
  20593. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20594. observable.notifyObservers(info, renderingGroupMask);
  20595. }
  20596. if (renderingGroup)
  20597. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20598. // Fire POSTTRANSPARENT stage
  20599. if (observable && info) {
  20600. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20601. observable.notifyObservers(info, renderingGroupMask);
  20602. }
  20603. }
  20604. };
  20605. RenderingManager.prototype.reset = function () {
  20606. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20607. var renderingGroup = this._renderingGroups[index];
  20608. if (renderingGroup) {
  20609. renderingGroup.prepare();
  20610. }
  20611. }
  20612. };
  20613. RenderingManager.prototype.dispose = function () {
  20614. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20615. var renderingGroup = this._renderingGroups[index];
  20616. if (renderingGroup) {
  20617. renderingGroup.dispose();
  20618. }
  20619. }
  20620. this._renderingGroups.length = 0;
  20621. };
  20622. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20623. if (this._renderingGroups[renderingGroupId] === undefined) {
  20624. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20625. }
  20626. };
  20627. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20628. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20629. this._prepareRenderingGroup(renderingGroupId);
  20630. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20631. };
  20632. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20633. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20634. this._prepareRenderingGroup(renderingGroupId);
  20635. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20636. };
  20637. /**
  20638. * @param subMesh The submesh to dispatch
  20639. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20640. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20641. */
  20642. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20643. if (mesh === undefined) {
  20644. mesh = subMesh.getMesh();
  20645. }
  20646. var renderingGroupId = mesh.renderingGroupId || 0;
  20647. this._prepareRenderingGroup(renderingGroupId);
  20648. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20649. };
  20650. /**
  20651. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20652. * This allowed control for front to back rendering or reversly depending of the special needs.
  20653. *
  20654. * @param renderingGroupId The rendering group id corresponding to its index
  20655. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20656. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20657. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20658. */
  20659. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20660. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20661. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20662. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20663. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20664. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20665. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20666. if (this._renderingGroups[renderingGroupId]) {
  20667. var group = this._renderingGroups[renderingGroupId];
  20668. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20669. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20670. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20671. }
  20672. };
  20673. /**
  20674. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20675. *
  20676. * @param renderingGroupId The rendering group id corresponding to its index
  20677. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20678. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20679. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20680. */
  20681. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20682. if (depth === void 0) { depth = true; }
  20683. if (stencil === void 0) { stencil = true; }
  20684. this._autoClearDepthStencil[renderingGroupId] = {
  20685. autoClear: autoClearDepthStencil,
  20686. depth: depth,
  20687. stencil: stencil
  20688. };
  20689. };
  20690. /**
  20691. * The max id used for rendering groups (not included)
  20692. */
  20693. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20694. /**
  20695. * The min id used for rendering groups (included)
  20696. */
  20697. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20698. /**
  20699. * Used to globally prevent autoclearing scenes.
  20700. */
  20701. RenderingManager.AUTOCLEAR = true;
  20702. return RenderingManager;
  20703. }());
  20704. BABYLON.RenderingManager = RenderingManager;
  20705. })(BABYLON || (BABYLON = {}));
  20706. //# sourceMappingURL=babylon.renderingManager.js.map
  20707. var BABYLON;
  20708. (function (BABYLON) {
  20709. var RenderingGroup = /** @class */ (function () {
  20710. /**
  20711. * Creates a new rendering group.
  20712. * @param index The rendering group index
  20713. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20714. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20715. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20716. */
  20717. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20721. this.index = index;
  20722. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20723. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20724. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20725. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20726. this._particleSystems = new BABYLON.SmartArray(256);
  20727. this._spriteManagers = new BABYLON.SmartArray(256);
  20728. this._edgesRenderers = new BABYLON.SmartArray(16);
  20729. this._scene = scene;
  20730. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20731. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20732. this.transparentSortCompareFn = transparentSortCompareFn;
  20733. }
  20734. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20735. /**
  20736. * Set the opaque sort comparison function.
  20737. * If null the sub meshes will be render in the order they were created
  20738. */
  20739. set: function (value) {
  20740. this._opaqueSortCompareFn = value;
  20741. if (value) {
  20742. this._renderOpaque = this.renderOpaqueSorted;
  20743. }
  20744. else {
  20745. this._renderOpaque = RenderingGroup.renderUnsorted;
  20746. }
  20747. },
  20748. enumerable: true,
  20749. configurable: true
  20750. });
  20751. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20752. /**
  20753. * Set the alpha test sort comparison function.
  20754. * If null the sub meshes will be render in the order they were created
  20755. */
  20756. set: function (value) {
  20757. this._alphaTestSortCompareFn = value;
  20758. if (value) {
  20759. this._renderAlphaTest = this.renderAlphaTestSorted;
  20760. }
  20761. else {
  20762. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20763. }
  20764. },
  20765. enumerable: true,
  20766. configurable: true
  20767. });
  20768. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20769. /**
  20770. * Set the transparent sort comparison function.
  20771. * If null the sub meshes will be render in the order they were created
  20772. */
  20773. set: function (value) {
  20774. if (value) {
  20775. this._transparentSortCompareFn = value;
  20776. }
  20777. else {
  20778. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20779. }
  20780. this._renderTransparent = this.renderTransparentSorted;
  20781. },
  20782. enumerable: true,
  20783. configurable: true
  20784. });
  20785. /**
  20786. * Render all the sub meshes contained in the group.
  20787. * @param customRenderFunction Used to override the default render behaviour of the group.
  20788. * @returns true if rendered some submeshes.
  20789. */
  20790. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20791. if (customRenderFunction) {
  20792. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20793. return;
  20794. }
  20795. var engine = this._scene.getEngine();
  20796. // Depth only
  20797. if (this._depthOnlySubMeshes.length !== 0) {
  20798. engine.setColorWrite(false);
  20799. this._renderAlphaTest(this._depthOnlySubMeshes);
  20800. engine.setColorWrite(true);
  20801. }
  20802. // Opaque
  20803. if (this._opaqueSubMeshes.length !== 0) {
  20804. this._renderOpaque(this._opaqueSubMeshes);
  20805. }
  20806. // Alpha test
  20807. if (this._alphaTestSubMeshes.length !== 0) {
  20808. this._renderAlphaTest(this._alphaTestSubMeshes);
  20809. }
  20810. var stencilState = engine.getStencilBuffer();
  20811. engine.setStencilBuffer(false);
  20812. // Sprites
  20813. if (renderSprites) {
  20814. this._renderSprites();
  20815. }
  20816. // Particles
  20817. if (renderParticles) {
  20818. this._renderParticles(activeMeshes);
  20819. }
  20820. if (this.onBeforeTransparentRendering) {
  20821. this.onBeforeTransparentRendering();
  20822. }
  20823. // Transparent
  20824. if (this._transparentSubMeshes.length !== 0) {
  20825. this._renderTransparent(this._transparentSubMeshes);
  20826. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20827. }
  20828. // Set back stencil to false in case it changes before the edge renderer.
  20829. engine.setStencilBuffer(false);
  20830. // Edges
  20831. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20832. this._edgesRenderers.data[edgesRendererIndex].render();
  20833. }
  20834. // Restore Stencil state.
  20835. engine.setStencilBuffer(stencilState);
  20836. };
  20837. /**
  20838. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20839. * @param subMeshes The submeshes to render
  20840. */
  20841. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20842. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20843. };
  20844. /**
  20845. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20846. * @param subMeshes The submeshes to render
  20847. */
  20848. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20849. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20850. };
  20851. /**
  20852. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20853. * @param subMeshes The submeshes to render
  20854. */
  20855. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20856. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20857. };
  20858. /**
  20859. * Renders the submeshes in a specified order.
  20860. * @param subMeshes The submeshes to sort before render
  20861. * @param sortCompareFn The comparison function use to sort
  20862. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20863. * @param transparent Specifies to activate blending if true
  20864. */
  20865. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20866. var subIndex = 0;
  20867. var subMesh;
  20868. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20869. for (; subIndex < subMeshes.length; subIndex++) {
  20870. subMesh = subMeshes.data[subIndex];
  20871. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20872. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20873. }
  20874. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20875. if (sortCompareFn) {
  20876. sortedArray.sort(sortCompareFn);
  20877. }
  20878. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20879. subMesh = sortedArray[subIndex];
  20880. if (transparent) {
  20881. var material = subMesh.getMaterial();
  20882. if (material && material.needDepthPrePass) {
  20883. var engine = material.getScene().getEngine();
  20884. engine.setColorWrite(false);
  20885. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20886. subMesh.render(false);
  20887. engine.setColorWrite(true);
  20888. }
  20889. }
  20890. subMesh.render(transparent);
  20891. }
  20892. };
  20893. /**
  20894. * Renders the submeshes in the order they were dispatched (no sort applied).
  20895. * @param subMeshes The submeshes to render
  20896. */
  20897. RenderingGroup.renderUnsorted = function (subMeshes) {
  20898. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20899. var submesh = subMeshes.data[subIndex];
  20900. submesh.render(false);
  20901. }
  20902. };
  20903. /**
  20904. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20905. * are rendered back to front if in the same alpha index.
  20906. *
  20907. * @param a The first submesh
  20908. * @param b The second submesh
  20909. * @returns The result of the comparison
  20910. */
  20911. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20912. // Alpha index first
  20913. if (a._alphaIndex > b._alphaIndex) {
  20914. return 1;
  20915. }
  20916. if (a._alphaIndex < b._alphaIndex) {
  20917. return -1;
  20918. }
  20919. // Then distance to camera
  20920. return RenderingGroup.backToFrontSortCompare(a, b);
  20921. };
  20922. /**
  20923. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20924. * are rendered back to front.
  20925. *
  20926. * @param a The first submesh
  20927. * @param b The second submesh
  20928. * @returns The result of the comparison
  20929. */
  20930. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20931. // Then distance to camera
  20932. if (a._distanceToCamera < b._distanceToCamera) {
  20933. return 1;
  20934. }
  20935. if (a._distanceToCamera > b._distanceToCamera) {
  20936. return -1;
  20937. }
  20938. return 0;
  20939. };
  20940. /**
  20941. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20942. * are rendered front to back (prevent overdraw).
  20943. *
  20944. * @param a The first submesh
  20945. * @param b The second submesh
  20946. * @returns The result of the comparison
  20947. */
  20948. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20949. // Then distance to camera
  20950. if (a._distanceToCamera < b._distanceToCamera) {
  20951. return -1;
  20952. }
  20953. if (a._distanceToCamera > b._distanceToCamera) {
  20954. return 1;
  20955. }
  20956. return 0;
  20957. };
  20958. /**
  20959. * Resets the different lists of submeshes to prepare a new frame.
  20960. */
  20961. RenderingGroup.prototype.prepare = function () {
  20962. this._opaqueSubMeshes.reset();
  20963. this._transparentSubMeshes.reset();
  20964. this._alphaTestSubMeshes.reset();
  20965. this._depthOnlySubMeshes.reset();
  20966. this._particleSystems.reset();
  20967. this._spriteManagers.reset();
  20968. this._edgesRenderers.reset();
  20969. };
  20970. RenderingGroup.prototype.dispose = function () {
  20971. this._opaqueSubMeshes.dispose();
  20972. this._transparentSubMeshes.dispose();
  20973. this._alphaTestSubMeshes.dispose();
  20974. this._depthOnlySubMeshes.dispose();
  20975. this._particleSystems.dispose();
  20976. this._spriteManagers.dispose();
  20977. this._edgesRenderers.dispose();
  20978. };
  20979. /**
  20980. * Inserts the submesh in its correct queue depending on its material.
  20981. * @param subMesh The submesh to dispatch
  20982. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20983. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20984. */
  20985. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20986. // Get mesh and materials if not provided
  20987. if (mesh === undefined) {
  20988. mesh = subMesh.getMesh();
  20989. }
  20990. if (material === undefined) {
  20991. material = subMesh.getMaterial();
  20992. }
  20993. if (material === null || material === undefined) {
  20994. return;
  20995. }
  20996. if (material.needAlphaBlendingForMesh(mesh)) {
  20997. this._transparentSubMeshes.push(subMesh);
  20998. }
  20999. else if (material.needAlphaTesting()) {
  21000. if (material.needDepthPrePass) {
  21001. this._depthOnlySubMeshes.push(subMesh);
  21002. }
  21003. this._alphaTestSubMeshes.push(subMesh);
  21004. }
  21005. else {
  21006. if (material.needDepthPrePass) {
  21007. this._depthOnlySubMeshes.push(subMesh);
  21008. }
  21009. this._opaqueSubMeshes.push(subMesh); // Opaque
  21010. }
  21011. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21012. this._edgesRenderers.push(mesh._edgesRenderer);
  21013. }
  21014. };
  21015. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21016. this._spriteManagers.push(spriteManager);
  21017. };
  21018. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21019. this._particleSystems.push(particleSystem);
  21020. };
  21021. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21022. if (this._particleSystems.length === 0) {
  21023. return;
  21024. }
  21025. // Particles
  21026. var activeCamera = this._scene.activeCamera;
  21027. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21028. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21029. var particleSystem = this._particleSystems.data[particleIndex];
  21030. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21031. continue;
  21032. }
  21033. var emitter = particleSystem.emitter;
  21034. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21035. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21036. }
  21037. }
  21038. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21039. };
  21040. RenderingGroup.prototype._renderSprites = function () {
  21041. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21042. return;
  21043. }
  21044. // Sprites
  21045. var activeCamera = this._scene.activeCamera;
  21046. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21047. for (var id = 0; id < this._spriteManagers.length; id++) {
  21048. var spriteManager = this._spriteManagers.data[id];
  21049. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21050. spriteManager.render();
  21051. }
  21052. }
  21053. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21054. };
  21055. return RenderingGroup;
  21056. }());
  21057. BABYLON.RenderingGroup = RenderingGroup;
  21058. })(BABYLON || (BABYLON = {}));
  21059. //# sourceMappingURL=babylon.renderingGroup.js.map
  21060. var BABYLON;
  21061. (function (BABYLON) {
  21062. var ClickInfo = /** @class */ (function () {
  21063. function ClickInfo() {
  21064. this._singleClick = false;
  21065. this._doubleClick = false;
  21066. this._hasSwiped = false;
  21067. this._ignore = false;
  21068. }
  21069. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21070. get: function () {
  21071. return this._singleClick;
  21072. },
  21073. set: function (b) {
  21074. this._singleClick = b;
  21075. },
  21076. enumerable: true,
  21077. configurable: true
  21078. });
  21079. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21080. get: function () {
  21081. return this._doubleClick;
  21082. },
  21083. set: function (b) {
  21084. this._doubleClick = b;
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21090. get: function () {
  21091. return this._hasSwiped;
  21092. },
  21093. set: function (b) {
  21094. this._hasSwiped = b;
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21100. get: function () {
  21101. return this._ignore;
  21102. },
  21103. set: function (b) {
  21104. this._ignore = b;
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. return ClickInfo;
  21110. }());
  21111. /**
  21112. * This class is used by the onRenderingGroupObservable
  21113. */
  21114. var RenderingGroupInfo = /** @class */ (function () {
  21115. function RenderingGroupInfo() {
  21116. }
  21117. /**
  21118. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21119. * This stage will be fired no matter what
  21120. */
  21121. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21122. /**
  21123. * Called before opaque object are rendered.
  21124. * This stage will be fired only if there's 3D Opaque content to render
  21125. */
  21126. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21127. /**
  21128. * Called after the opaque objects are rendered and before the transparent ones
  21129. * This stage will be fired only if there's 3D transparent content to render
  21130. */
  21131. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21132. /**
  21133. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21134. * This stage will be fired no matter what
  21135. */
  21136. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21137. return RenderingGroupInfo;
  21138. }());
  21139. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21140. /**
  21141. * Represents a scene to be rendered by the engine.
  21142. * @see http://doc.babylonjs.com/page.php?p=21911
  21143. */
  21144. var Scene = /** @class */ (function () {
  21145. /**
  21146. * @constructor
  21147. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21148. */
  21149. function Scene(engine) {
  21150. // Members
  21151. this.autoClear = true;
  21152. this.autoClearDepthAndStencil = true;
  21153. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21154. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21155. this.forceWireframe = false;
  21156. this._forcePointsCloud = false;
  21157. this.forceShowBoundingBoxes = false;
  21158. this.animationsEnabled = true;
  21159. this.useConstantAnimationDeltaTime = false;
  21160. this.constantlyUpdateMeshUnderPointer = false;
  21161. this.hoverCursor = "pointer";
  21162. this.defaultCursor = "";
  21163. /**
  21164. * This is used to call preventDefault() on pointer down
  21165. * in order to block unwanted artifacts like system double clicks
  21166. */
  21167. this.preventDefaultOnPointerDown = true;
  21168. // Metadata
  21169. this.metadata = null;
  21170. /**
  21171. * An event triggered when the scene is disposed.
  21172. * @type {BABYLON.Observable}
  21173. */
  21174. this.onDisposeObservable = new BABYLON.Observable();
  21175. /**
  21176. * An event triggered before rendering the scene (right after animations and physics)
  21177. * @type {BABYLON.Observable}
  21178. */
  21179. this.onBeforeRenderObservable = new BABYLON.Observable();
  21180. /**
  21181. * An event triggered after rendering the scene
  21182. * @type {BABYLON.Observable}
  21183. */
  21184. this.onAfterRenderObservable = new BABYLON.Observable();
  21185. /**
  21186. * An event triggered before animating the scene
  21187. * @type {BABYLON.Observable}
  21188. */
  21189. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21190. /**
  21191. * An event triggered after animations processing
  21192. * @type {BABYLON.Observable}
  21193. */
  21194. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21195. /**
  21196. * An event triggered before draw calls are ready to be sent
  21197. * @type {BABYLON.Observable}
  21198. */
  21199. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21200. /**
  21201. * An event triggered after draw calls have been sent
  21202. * @type {BABYLON.Observable}
  21203. */
  21204. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21205. /**
  21206. * An event triggered when physic simulation is about to be run
  21207. * @type {BABYLON.Observable}
  21208. */
  21209. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21210. /**
  21211. * An event triggered when physic simulation has been done
  21212. * @type {BABYLON.Observable}
  21213. */
  21214. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21215. /**
  21216. * An event triggered when the scene is ready
  21217. * @type {BABYLON.Observable}
  21218. */
  21219. this.onReadyObservable = new BABYLON.Observable();
  21220. /**
  21221. * An event triggered before rendering a camera
  21222. * @type {BABYLON.Observable}
  21223. */
  21224. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21225. /**
  21226. * An event triggered after rendering a camera
  21227. * @type {BABYLON.Observable}
  21228. */
  21229. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21230. /**
  21231. * An event triggered when active meshes evaluation is about to start
  21232. * @type {BABYLON.Observable}
  21233. */
  21234. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21235. /**
  21236. * An event triggered when active meshes evaluation is done
  21237. * @type {BABYLON.Observable}
  21238. */
  21239. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21240. /**
  21241. * An event triggered when particles rendering is about to start
  21242. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21243. * @type {BABYLON.Observable}
  21244. */
  21245. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21246. /**
  21247. * An event triggered when particles rendering is done
  21248. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21249. * @type {BABYLON.Observable}
  21250. */
  21251. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21252. /**
  21253. * An event triggered when sprites rendering is about to start
  21254. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21255. * @type {BABYLON.Observable}
  21256. */
  21257. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21258. /**
  21259. * An event triggered when sprites rendering is done
  21260. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21261. * @type {BABYLON.Observable}
  21262. */
  21263. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21264. /**
  21265. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21266. * @type {BABYLON.Observable}
  21267. */
  21268. this.onDataLoadedObservable = new BABYLON.Observable();
  21269. /**
  21270. * An event triggered when a camera is created
  21271. * @type {BABYLON.Observable}
  21272. */
  21273. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21274. /**
  21275. * An event triggered when a camera is removed
  21276. * @type {BABYLON.Observable}
  21277. */
  21278. this.onCameraRemovedObservable = new BABYLON.Observable();
  21279. /**
  21280. * An event triggered when a light is created
  21281. * @type {BABYLON.Observable}
  21282. */
  21283. this.onNewLightAddedObservable = new BABYLON.Observable();
  21284. /**
  21285. * An event triggered when a light is removed
  21286. * @type {BABYLON.Observable}
  21287. */
  21288. this.onLightRemovedObservable = new BABYLON.Observable();
  21289. /**
  21290. * An event triggered when a geometry is created
  21291. * @type {BABYLON.Observable}
  21292. */
  21293. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21294. /**
  21295. * An event triggered when a geometry is removed
  21296. * @type {BABYLON.Observable}
  21297. */
  21298. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21299. /**
  21300. * An event triggered when a transform node is created
  21301. * @type {BABYLON.Observable}
  21302. */
  21303. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21304. /**
  21305. * An event triggered when a transform node is removed
  21306. * @type {BABYLON.Observable}
  21307. */
  21308. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21309. /**
  21310. * An event triggered when a mesh is created
  21311. * @type {BABYLON.Observable}
  21312. */
  21313. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21314. /**
  21315. * An event triggered when a mesh is removed
  21316. * @type {BABYLON.Observable}
  21317. */
  21318. this.onMeshRemovedObservable = new BABYLON.Observable();
  21319. /**
  21320. * An event triggered when render targets are about to be rendered
  21321. * Can happen multiple times per frame.
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered when render targets were rendered.
  21327. * Can happen multiple times per frame.
  21328. * @type {BABYLON.Observable}
  21329. */
  21330. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21331. /**
  21332. * An event triggered before calculating deterministic simulation step
  21333. * @type {BABYLON.Observable}
  21334. */
  21335. this.onBeforeStepObservable = new BABYLON.Observable();
  21336. /**
  21337. * An event triggered after calculating deterministic simulation step
  21338. * @type {BABYLON.Observable}
  21339. */
  21340. this.onAfterStepObservable = new BABYLON.Observable();
  21341. /**
  21342. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21343. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21344. * 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)
  21345. */
  21346. this.onRenderingGroupObservable = new BABYLON.Observable();
  21347. // Animations
  21348. this.animations = [];
  21349. /**
  21350. * 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).
  21351. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21352. */
  21353. this.onPrePointerObservable = new BABYLON.Observable();
  21354. /**
  21355. * Observable event triggered each time an input event is received from the rendering canvas
  21356. */
  21357. this.onPointerObservable = new BABYLON.Observable();
  21358. this._meshPickProceed = false;
  21359. this._currentPickResult = null;
  21360. this._previousPickResult = null;
  21361. this._totalPointersPressed = 0;
  21362. this._doubleClickOccured = false;
  21363. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21364. this.cameraToUseForPointers = null;
  21365. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21366. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21367. this._startingPointerTime = 0;
  21368. this._previousStartingPointerTime = 0;
  21369. // Deterministic lockstep
  21370. this._timeAccumulator = 0;
  21371. this._currentStepId = 0;
  21372. this._currentInternalStep = 0;
  21373. // Keyboard
  21374. /**
  21375. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21376. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21377. */
  21378. this.onPreKeyboardObservable = new BABYLON.Observable();
  21379. /**
  21380. * Observable event triggered each time an keyboard event is received from the hosting window
  21381. */
  21382. this.onKeyboardObservable = new BABYLON.Observable();
  21383. // Coordinate system
  21384. /**
  21385. * use right-handed coordinate system on this scene.
  21386. * @type {boolean}
  21387. */
  21388. this._useRightHandedSystem = false;
  21389. // Fog
  21390. this._fogEnabled = true;
  21391. this._fogMode = Scene.FOGMODE_NONE;
  21392. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21393. this.fogDensity = 0.1;
  21394. this.fogStart = 0;
  21395. this.fogEnd = 1000.0;
  21396. // Lights
  21397. /**
  21398. * is shadow enabled on this scene.
  21399. * @type {boolean}
  21400. */
  21401. this._shadowsEnabled = true;
  21402. /**
  21403. * is light enabled on this scene.
  21404. * @type {boolean}
  21405. */
  21406. this._lightsEnabled = true;
  21407. /**
  21408. * All of the lights added to this scene.
  21409. * @see BABYLON.Light
  21410. * @type {BABYLON.Light[]}
  21411. */
  21412. this.lights = new Array();
  21413. // Cameras
  21414. /** All of the cameras added to this scene. */
  21415. this.cameras = new Array();
  21416. /** All of the active cameras added to this scene. */
  21417. this.activeCameras = new Array();
  21418. // Meshes
  21419. /**
  21420. * All of the tranform nodes added to this scene.
  21421. * @see BABYLON.TransformNode
  21422. * @type {BABYLON.TransformNode[]}
  21423. */
  21424. this.transformNodes = new Array();
  21425. /**
  21426. * All of the (abstract) meshes added to this scene.
  21427. * @see BABYLON.AbstractMesh
  21428. * @type {BABYLON.AbstractMesh[]}
  21429. */
  21430. this.meshes = new Array();
  21431. /**
  21432. * All of the animation groups added to this scene.
  21433. * @see BABYLON.AnimationGroup
  21434. * @type {BABYLON.AnimationGroup[]}
  21435. */
  21436. this.animationGroups = new Array();
  21437. // Geometries
  21438. this._geometries = new Array();
  21439. this.materials = new Array();
  21440. this.multiMaterials = new Array();
  21441. // Textures
  21442. this._texturesEnabled = true;
  21443. this.textures = new Array();
  21444. // Particles
  21445. this.particlesEnabled = true;
  21446. this.particleSystems = new Array();
  21447. // Sprites
  21448. this.spritesEnabled = true;
  21449. this.spriteManagers = new Array();
  21450. /**
  21451. * The list of layers (background and foreground) of the scene.
  21452. */
  21453. this.layers = new Array();
  21454. /**
  21455. * The list of effect layers (highlights/glow) contained in the scene.
  21456. */
  21457. this.effectLayers = new Array();
  21458. // Skeletons
  21459. this._skeletonsEnabled = true;
  21460. this.skeletons = new Array();
  21461. // Morph targets
  21462. this.morphTargetManagers = new Array();
  21463. // Lens flares
  21464. this.lensFlaresEnabled = true;
  21465. this.lensFlareSystems = new Array();
  21466. // Collisions
  21467. this.collisionsEnabled = true;
  21468. /** Defines the gravity applied to this scene */
  21469. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21470. // Postprocesses
  21471. this.postProcesses = new Array();
  21472. this.postProcessesEnabled = true;
  21473. // Customs render targets
  21474. this.renderTargetsEnabled = true;
  21475. this.dumpNextRenderTargets = false;
  21476. this.customRenderTargets = new Array();
  21477. // Imported meshes
  21478. this.importedMeshesFiles = new Array();
  21479. // Probes
  21480. this.probesEnabled = true;
  21481. this.reflectionProbes = new Array();
  21482. this._actionManagers = new Array();
  21483. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21484. // Procedural textures
  21485. this.proceduralTexturesEnabled = true;
  21486. this._proceduralTextures = new Array();
  21487. this.soundTracks = new Array();
  21488. this._audioEnabled = true;
  21489. this._headphone = false;
  21490. // Performance counters
  21491. this._totalVertices = new BABYLON.PerfCounter();
  21492. this._activeIndices = new BABYLON.PerfCounter();
  21493. this._activeParticles = new BABYLON.PerfCounter();
  21494. this._activeBones = new BABYLON.PerfCounter();
  21495. this._animationTime = 0;
  21496. this.animationTimeScale = 1;
  21497. this._renderId = 0;
  21498. this._executeWhenReadyTimeoutId = -1;
  21499. this._intermediateRendering = false;
  21500. this._viewUpdateFlag = -1;
  21501. this._projectionUpdateFlag = -1;
  21502. this._alternateViewUpdateFlag = -1;
  21503. this._alternateProjectionUpdateFlag = -1;
  21504. this._toBeDisposed = new BABYLON.SmartArray(256);
  21505. this._activeRequests = new Array();
  21506. this._pendingData = new Array();
  21507. this._isDisposed = false;
  21508. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21509. this._activeMeshes = new BABYLON.SmartArray(256);
  21510. this._processedMaterials = new BABYLON.SmartArray(256);
  21511. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21512. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21513. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21514. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21515. this._activeAnimatables = new Array();
  21516. this._transformMatrix = BABYLON.Matrix.Zero();
  21517. this._useAlternateCameraConfiguration = false;
  21518. this._alternateRendering = false;
  21519. this.requireLightSorting = false;
  21520. this._depthRenderer = {};
  21521. this._activeMeshesFrozen = false;
  21522. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21523. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21524. this._engine.scenes.push(this);
  21525. this._uid = null;
  21526. this._renderingManager = new BABYLON.RenderingManager(this);
  21527. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21528. if (BABYLON.OutlineRenderer) {
  21529. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21530. }
  21531. if (BABYLON.Tools.IsWindowObjectExist()) {
  21532. this.attachControl();
  21533. }
  21534. //simplification queue
  21535. if (BABYLON.SimplificationQueue) {
  21536. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21537. }
  21538. //collision coordinator initialization. For now legacy per default.
  21539. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21540. // Uniform Buffer
  21541. this._createUbo();
  21542. // Default Image processing definition.
  21543. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21544. }
  21545. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21546. /** The fog is deactivated */
  21547. get: function () {
  21548. return Scene._FOGMODE_NONE;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21554. /** The fog density is following an exponential function */
  21555. get: function () {
  21556. return Scene._FOGMODE_EXP;
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21562. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21563. get: function () {
  21564. return Scene._FOGMODE_EXP2;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21570. /** The fog density is following a linear function. */
  21571. get: function () {
  21572. return Scene._FOGMODE_LINEAR;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21578. /**
  21579. * Texture used in all pbr material as the reflection texture.
  21580. * As in the majority of the scene they are the same (exception for multi room and so on),
  21581. * this is easier to reference from here than from all the materials.
  21582. */
  21583. get: function () {
  21584. return this._environmentTexture;
  21585. },
  21586. /**
  21587. * Texture used in all pbr material as the reflection texture.
  21588. * As in the majority of the scene they are the same (exception for multi room and so on),
  21589. * this is easier to set here than in all the materials.
  21590. */
  21591. set: function (value) {
  21592. if (this._environmentTexture === value) {
  21593. return;
  21594. }
  21595. this._environmentTexture = value;
  21596. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21597. },
  21598. enumerable: true,
  21599. configurable: true
  21600. });
  21601. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21602. /**
  21603. * Default image processing configuration used either in the rendering
  21604. * Forward main pass or through the imageProcessingPostProcess if present.
  21605. * As in the majority of the scene they are the same (exception for multi camera),
  21606. * this is easier to reference from here than from all the materials and post process.
  21607. *
  21608. * No setter as we it is a shared configuration, you can set the values instead.
  21609. */
  21610. get: function () {
  21611. return this._imageProcessingConfiguration;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21617. get: function () {
  21618. return this._forcePointsCloud;
  21619. },
  21620. set: function (value) {
  21621. if (this._forcePointsCloud === value) {
  21622. return;
  21623. }
  21624. this._forcePointsCloud = value;
  21625. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene.prototype, "onDispose", {
  21631. /** A function to be executed when this scene is disposed. */
  21632. set: function (callback) {
  21633. if (this._onDisposeObserver) {
  21634. this.onDisposeObservable.remove(this._onDisposeObserver);
  21635. }
  21636. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Scene.prototype, "beforeRender", {
  21642. /** A function to be executed before rendering this scene */
  21643. set: function (callback) {
  21644. if (this._onBeforeRenderObserver) {
  21645. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21646. }
  21647. if (callback) {
  21648. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21649. }
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(Scene.prototype, "afterRender", {
  21655. /** A function to be executed after rendering this scene */
  21656. set: function (callback) {
  21657. if (this._onAfterRenderObserver) {
  21658. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21659. }
  21660. if (callback) {
  21661. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21662. }
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21668. set: function (callback) {
  21669. if (this._onBeforeCameraRenderObserver) {
  21670. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21671. }
  21672. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21673. },
  21674. enumerable: true,
  21675. configurable: true
  21676. });
  21677. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21678. set: function (callback) {
  21679. if (this._onAfterCameraRenderObserver) {
  21680. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21681. }
  21682. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21688. get: function () {
  21689. if (!this._gamepadManager) {
  21690. this._gamepadManager = new BABYLON.GamepadManager(this);
  21691. }
  21692. return this._gamepadManager;
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21698. get: function () {
  21699. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21700. },
  21701. enumerable: true,
  21702. configurable: true
  21703. });
  21704. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21705. get: function () {
  21706. return this._useRightHandedSystem;
  21707. },
  21708. set: function (value) {
  21709. if (this._useRightHandedSystem === value) {
  21710. return;
  21711. }
  21712. this._useRightHandedSystem = value;
  21713. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Scene.prototype.setStepId = function (newStepId) {
  21719. this._currentStepId = newStepId;
  21720. };
  21721. ;
  21722. Scene.prototype.getStepId = function () {
  21723. return this._currentStepId;
  21724. };
  21725. ;
  21726. Scene.prototype.getInternalStep = function () {
  21727. return this._currentInternalStep;
  21728. };
  21729. ;
  21730. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21731. get: function () {
  21732. return this._fogEnabled;
  21733. },
  21734. /**
  21735. * is fog enabled on this scene.
  21736. */
  21737. set: function (value) {
  21738. if (this._fogEnabled === value) {
  21739. return;
  21740. }
  21741. this._fogEnabled = value;
  21742. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21743. },
  21744. enumerable: true,
  21745. configurable: true
  21746. });
  21747. Object.defineProperty(Scene.prototype, "fogMode", {
  21748. get: function () {
  21749. return this._fogMode;
  21750. },
  21751. set: function (value) {
  21752. if (this._fogMode === value) {
  21753. return;
  21754. }
  21755. this._fogMode = value;
  21756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21762. get: function () {
  21763. return this._shadowsEnabled;
  21764. },
  21765. set: function (value) {
  21766. if (this._shadowsEnabled === value) {
  21767. return;
  21768. }
  21769. this._shadowsEnabled = value;
  21770. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21776. get: function () {
  21777. return this._lightsEnabled;
  21778. },
  21779. set: function (value) {
  21780. if (this._lightsEnabled === value) {
  21781. return;
  21782. }
  21783. this._lightsEnabled = value;
  21784. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21790. /** The default material used on meshes when no material is affected */
  21791. get: function () {
  21792. if (!this._defaultMaterial) {
  21793. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21794. }
  21795. return this._defaultMaterial;
  21796. },
  21797. /** The default material used on meshes when no material is affected */
  21798. set: function (value) {
  21799. this._defaultMaterial = value;
  21800. },
  21801. enumerable: true,
  21802. configurable: true
  21803. });
  21804. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21805. get: function () {
  21806. return this._texturesEnabled;
  21807. },
  21808. set: function (value) {
  21809. if (this._texturesEnabled === value) {
  21810. return;
  21811. }
  21812. this._texturesEnabled = value;
  21813. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21819. get: function () {
  21820. return this._skeletonsEnabled;
  21821. },
  21822. set: function (value) {
  21823. if (this._skeletonsEnabled === value) {
  21824. return;
  21825. }
  21826. this._skeletonsEnabled = value;
  21827. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21833. get: function () {
  21834. if (!this._postProcessRenderPipelineManager) {
  21835. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21836. }
  21837. return this._postProcessRenderPipelineManager;
  21838. },
  21839. enumerable: true,
  21840. configurable: true
  21841. });
  21842. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21843. get: function () {
  21844. if (!this._mainSoundTrack) {
  21845. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21846. }
  21847. return this._mainSoundTrack;
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21853. get: function () {
  21854. return this._alternateRendering;
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21860. get: function () {
  21861. return this._frustumPlanes;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21867. /**
  21868. * Gets the current geometry buffer associated to the scene.
  21869. */
  21870. get: function () {
  21871. return this._geometryBufferRenderer;
  21872. },
  21873. /**
  21874. * Sets the current geometry buffer for the scene.
  21875. */
  21876. set: function (geometryBufferRenderer) {
  21877. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21878. this._geometryBufferRenderer = geometryBufferRenderer;
  21879. }
  21880. },
  21881. enumerable: true,
  21882. configurable: true
  21883. });
  21884. Object.defineProperty(Scene.prototype, "debugLayer", {
  21885. // Properties
  21886. get: function () {
  21887. if (!this._debugLayer) {
  21888. this._debugLayer = new BABYLON.DebugLayer(this);
  21889. }
  21890. return this._debugLayer;
  21891. },
  21892. enumerable: true,
  21893. configurable: true
  21894. });
  21895. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21896. get: function () {
  21897. return this._workerCollisions;
  21898. },
  21899. set: function (enabled) {
  21900. if (!BABYLON.CollisionCoordinatorLegacy) {
  21901. return;
  21902. }
  21903. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21904. this._workerCollisions = enabled;
  21905. if (this.collisionCoordinator) {
  21906. this.collisionCoordinator.destroy();
  21907. }
  21908. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21909. this.collisionCoordinator.init(this);
  21910. },
  21911. enumerable: true,
  21912. configurable: true
  21913. });
  21914. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21915. get: function () {
  21916. return this._selectionOctree;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21922. /**
  21923. * The mesh that is currently under the pointer.
  21924. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21925. */
  21926. get: function () {
  21927. return this._pointerOverMesh;
  21928. },
  21929. enumerable: true,
  21930. configurable: true
  21931. });
  21932. Object.defineProperty(Scene.prototype, "pointerX", {
  21933. /**
  21934. * Current on-screen X position of the pointer
  21935. * @return {number} X position of the pointer
  21936. */
  21937. get: function () {
  21938. return this._pointerX;
  21939. },
  21940. enumerable: true,
  21941. configurable: true
  21942. });
  21943. Object.defineProperty(Scene.prototype, "pointerY", {
  21944. /**
  21945. * Current on-screen Y position of the pointer
  21946. * @return {number} Y position of the pointer
  21947. */
  21948. get: function () {
  21949. return this._pointerY;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Scene.prototype.getCachedMaterial = function () {
  21955. return this._cachedMaterial;
  21956. };
  21957. Scene.prototype.getCachedEffect = function () {
  21958. return this._cachedEffect;
  21959. };
  21960. Scene.prototype.getCachedVisibility = function () {
  21961. return this._cachedVisibility;
  21962. };
  21963. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21964. if (visibility === void 0) { visibility = 1; }
  21965. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21966. };
  21967. Scene.prototype.getBoundingBoxRenderer = function () {
  21968. if (!this._boundingBoxRenderer) {
  21969. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21970. }
  21971. return this._boundingBoxRenderer;
  21972. };
  21973. Scene.prototype.getOutlineRenderer = function () {
  21974. return this._outlineRenderer;
  21975. };
  21976. Scene.prototype.getEngine = function () {
  21977. return this._engine;
  21978. };
  21979. Scene.prototype.getTotalVertices = function () {
  21980. return this._totalVertices.current;
  21981. };
  21982. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21983. get: function () {
  21984. return this._totalVertices;
  21985. },
  21986. enumerable: true,
  21987. configurable: true
  21988. });
  21989. Scene.prototype.getActiveIndices = function () {
  21990. return this._activeIndices.current;
  21991. };
  21992. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21993. get: function () {
  21994. return this._activeIndices;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Scene.prototype.getActiveParticles = function () {
  22000. return this._activeParticles.current;
  22001. };
  22002. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22003. get: function () {
  22004. return this._activeParticles;
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Scene.prototype.getActiveBones = function () {
  22010. return this._activeBones.current;
  22011. };
  22012. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22013. get: function () {
  22014. return this._activeBones;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. // Stats
  22020. Scene.prototype.getInterFramePerfCounter = function () {
  22021. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22022. return 0;
  22023. };
  22024. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22025. get: function () {
  22026. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22027. return null;
  22028. },
  22029. enumerable: true,
  22030. configurable: true
  22031. });
  22032. Scene.prototype.getLastFrameDuration = function () {
  22033. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22034. return 0;
  22035. };
  22036. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22037. get: function () {
  22038. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22039. return null;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22045. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22046. return 0;
  22047. };
  22048. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22049. get: function () {
  22050. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22051. return null;
  22052. },
  22053. enumerable: true,
  22054. configurable: true
  22055. });
  22056. Scene.prototype.getActiveMeshes = function () {
  22057. return this._activeMeshes;
  22058. };
  22059. Scene.prototype.getRenderTargetsDuration = function () {
  22060. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22061. return 0;
  22062. };
  22063. Scene.prototype.getRenderDuration = function () {
  22064. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22065. return 0;
  22066. };
  22067. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22068. get: function () {
  22069. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22070. return null;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Scene.prototype.getParticlesDuration = function () {
  22076. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22077. return 0;
  22078. };
  22079. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22080. get: function () {
  22081. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22082. return null;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Scene.prototype.getSpritesDuration = function () {
  22088. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22089. return 0;
  22090. };
  22091. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22092. get: function () {
  22093. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22094. return null;
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Scene.prototype.getAnimationRatio = function () {
  22100. return this._animationRatio;
  22101. };
  22102. Scene.prototype.getRenderId = function () {
  22103. return this._renderId;
  22104. };
  22105. Scene.prototype.incrementRenderId = function () {
  22106. this._renderId++;
  22107. };
  22108. Scene.prototype._updatePointerPosition = function (evt) {
  22109. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22110. if (!canvasRect) {
  22111. return;
  22112. }
  22113. this._pointerX = evt.clientX - canvasRect.left;
  22114. this._pointerY = evt.clientY - canvasRect.top;
  22115. this._unTranslatedPointerX = this._pointerX;
  22116. this._unTranslatedPointerY = this._pointerY;
  22117. };
  22118. Scene.prototype._createUbo = function () {
  22119. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22120. this._sceneUbo.addUniform("viewProjection", 16);
  22121. this._sceneUbo.addUniform("view", 16);
  22122. };
  22123. Scene.prototype._createAlternateUbo = function () {
  22124. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22125. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22126. this._alternateSceneUbo.addUniform("view", 16);
  22127. };
  22128. // Pointers handling
  22129. /**
  22130. * Use this method to simulate a pointer move on a mesh
  22131. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22132. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22133. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22134. */
  22135. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22136. var evt = new PointerEvent("pointermove", pointerEventInit);
  22137. return this._processPointerMove(pickResult, evt);
  22138. };
  22139. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22140. var canvas = this._engine.getRenderingCanvas();
  22141. if (!canvas) {
  22142. return this;
  22143. }
  22144. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22145. this.setPointerOverSprite(null);
  22146. this.setPointerOverMesh(pickResult.pickedMesh);
  22147. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22148. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22149. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22150. }
  22151. else {
  22152. canvas.style.cursor = this.hoverCursor;
  22153. }
  22154. }
  22155. else {
  22156. canvas.style.cursor = this.defaultCursor;
  22157. }
  22158. }
  22159. else {
  22160. this.setPointerOverMesh(null);
  22161. // Sprites
  22162. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22163. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22164. this.setPointerOverSprite(pickResult.pickedSprite);
  22165. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22166. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22167. }
  22168. else {
  22169. canvas.style.cursor = this.hoverCursor;
  22170. }
  22171. }
  22172. else {
  22173. this.setPointerOverSprite(null);
  22174. // Restore pointer
  22175. canvas.style.cursor = this.defaultCursor;
  22176. }
  22177. }
  22178. if (pickResult) {
  22179. if (this.onPointerMove) {
  22180. this.onPointerMove(evt, pickResult);
  22181. }
  22182. if (this.onPointerObservable.hasObservers()) {
  22183. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22184. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22185. this.onPointerObservable.notifyObservers(pi, type);
  22186. }
  22187. }
  22188. return this;
  22189. };
  22190. /**
  22191. * Use this method to simulate a pointer down on a mesh
  22192. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22193. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22194. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22195. */
  22196. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22197. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22198. return this._processPointerDown(pickResult, evt);
  22199. };
  22200. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22201. var _this = this;
  22202. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22203. this._pickedDownMesh = pickResult.pickedMesh;
  22204. var actionManager = pickResult.pickedMesh.actionManager;
  22205. if (actionManager) {
  22206. if (actionManager.hasPickTriggers) {
  22207. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22208. switch (evt.button) {
  22209. case 0:
  22210. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22211. break;
  22212. case 1:
  22213. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22214. break;
  22215. case 2:
  22216. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22217. break;
  22218. }
  22219. }
  22220. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22221. window.setTimeout(function () {
  22222. 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);
  22223. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22224. if (_this._totalPointersPressed !== 0 &&
  22225. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22226. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22227. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22228. _this._startingPointerTime = 0;
  22229. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22230. }
  22231. }
  22232. }, Scene.LongPressDelay);
  22233. }
  22234. }
  22235. }
  22236. if (pickResult) {
  22237. if (this.onPointerDown) {
  22238. this.onPointerDown(evt, pickResult);
  22239. }
  22240. if (this.onPointerObservable.hasObservers()) {
  22241. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22242. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22243. this.onPointerObservable.notifyObservers(pi, type);
  22244. }
  22245. }
  22246. return this;
  22247. };
  22248. /**
  22249. * Use this method to simulate a pointer up on a mesh
  22250. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22251. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22252. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22253. */
  22254. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22255. var evt = new PointerEvent("pointerup", pointerEventInit);
  22256. var clickInfo = new ClickInfo();
  22257. clickInfo.singleClick = true;
  22258. clickInfo.ignore = true;
  22259. return this._processPointerUp(pickResult, evt, clickInfo);
  22260. };
  22261. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22262. if (pickResult && pickResult && pickResult.pickedMesh) {
  22263. this._pickedUpMesh = pickResult.pickedMesh;
  22264. if (this._pickedDownMesh === this._pickedUpMesh) {
  22265. if (this.onPointerPick) {
  22266. this.onPointerPick(evt, pickResult);
  22267. }
  22268. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22269. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22270. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22271. this.onPointerObservable.notifyObservers(pi, type);
  22272. }
  22273. }
  22274. if (pickResult.pickedMesh.actionManager) {
  22275. if (clickInfo.ignore) {
  22276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22277. }
  22278. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22279. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22280. }
  22281. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22283. }
  22284. }
  22285. }
  22286. if (this._pickedDownMesh &&
  22287. this._pickedDownMesh.actionManager &&
  22288. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22289. this._pickedDownMesh !== this._pickedUpMesh) {
  22290. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22291. }
  22292. if (this.onPointerUp) {
  22293. this.onPointerUp(evt, pickResult);
  22294. }
  22295. if (this.onPointerObservable.hasObservers()) {
  22296. if (!clickInfo.ignore) {
  22297. if (!clickInfo.hasSwiped) {
  22298. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22299. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22300. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22301. this.onPointerObservable.notifyObservers(pi, type);
  22302. }
  22303. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22304. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22305. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22306. this.onPointerObservable.notifyObservers(pi, type);
  22307. }
  22308. }
  22309. }
  22310. else {
  22311. var type = BABYLON.PointerEventTypes.POINTERUP;
  22312. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22313. this.onPointerObservable.notifyObservers(pi, type);
  22314. }
  22315. }
  22316. return this;
  22317. };
  22318. /**
  22319. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22320. * @param attachUp defines if you want to attach events to pointerup
  22321. * @param attachDown defines if you want to attach events to pointerdown
  22322. * @param attachMove defines if you want to attach events to pointermove
  22323. */
  22324. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22325. var _this = this;
  22326. if (attachUp === void 0) { attachUp = true; }
  22327. if (attachDown === void 0) { attachDown = true; }
  22328. if (attachMove === void 0) { attachMove = true; }
  22329. this._initActionManager = function (act, clickInfo) {
  22330. if (!_this._meshPickProceed) {
  22331. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22332. _this._currentPickResult = pickResult;
  22333. if (pickResult) {
  22334. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22335. }
  22336. _this._meshPickProceed = true;
  22337. }
  22338. return act;
  22339. };
  22340. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22341. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22342. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22343. btn !== _this._previousButtonPressed) {
  22344. _this._doubleClickOccured = false;
  22345. clickInfo.singleClick = true;
  22346. clickInfo.ignore = false;
  22347. cb(clickInfo, _this._currentPickResult);
  22348. }
  22349. };
  22350. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22351. var clickInfo = new ClickInfo();
  22352. _this._currentPickResult = null;
  22353. var act = null;
  22354. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22355. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22356. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22357. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22358. act = _this._initActionManager(act, clickInfo);
  22359. if (act)
  22360. checkPicking = act.hasPickTriggers;
  22361. }
  22362. if (checkPicking) {
  22363. var btn = evt.button;
  22364. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22365. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22366. if (!clickInfo.hasSwiped) {
  22367. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22368. if (!checkSingleClickImmediately) {
  22369. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22370. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22371. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22372. act = _this._initActionManager(act, clickInfo);
  22373. if (act)
  22374. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22375. }
  22376. }
  22377. if (checkSingleClickImmediately) {
  22378. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22379. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22380. btn !== _this._previousButtonPressed) {
  22381. clickInfo.singleClick = true;
  22382. cb(clickInfo, _this._currentPickResult);
  22383. }
  22384. }
  22385. else {
  22386. // wait that no double click has been raised during the double click delay
  22387. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22388. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22389. }
  22390. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22391. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22392. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22393. act = _this._initActionManager(act, clickInfo);
  22394. if (act)
  22395. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22396. }
  22397. if (checkDoubleClick) {
  22398. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22399. if (btn === _this._previousButtonPressed &&
  22400. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22401. !_this._doubleClickOccured) {
  22402. // pointer has not moved for 2 clicks, it's a double click
  22403. if (!clickInfo.hasSwiped &&
  22404. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22405. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22406. _this._previousStartingPointerTime = 0;
  22407. _this._doubleClickOccured = true;
  22408. clickInfo.doubleClick = true;
  22409. clickInfo.ignore = false;
  22410. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22411. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22412. }
  22413. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22414. cb(clickInfo, _this._currentPickResult);
  22415. }
  22416. else {
  22417. _this._doubleClickOccured = false;
  22418. _this._previousStartingPointerTime = _this._startingPointerTime;
  22419. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22420. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22421. _this._previousButtonPressed = btn;
  22422. if (Scene.ExclusiveDoubleClickMode) {
  22423. if (_this._previousDelayedSimpleClickTimeout) {
  22424. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22425. }
  22426. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22427. cb(clickInfo, _this._previousPickResult);
  22428. }
  22429. else {
  22430. cb(clickInfo, _this._currentPickResult);
  22431. }
  22432. }
  22433. }
  22434. else {
  22435. _this._doubleClickOccured = false;
  22436. _this._previousStartingPointerTime = _this._startingPointerTime;
  22437. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22438. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22439. _this._previousButtonPressed = btn;
  22440. }
  22441. }
  22442. }
  22443. }
  22444. clickInfo.ignore = true;
  22445. cb(clickInfo, _this._currentPickResult);
  22446. };
  22447. this._spritePredicate = function (sprite) {
  22448. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22449. };
  22450. this._onPointerMove = function (evt) {
  22451. _this._updatePointerPosition(evt);
  22452. // PreObservable support
  22453. if (_this.onPrePointerObservable.hasObservers()) {
  22454. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22455. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22456. _this.onPrePointerObservable.notifyObservers(pi, type);
  22457. if (pi.skipOnPointerObservable) {
  22458. return;
  22459. }
  22460. }
  22461. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22462. return;
  22463. }
  22464. if (!_this.pointerMovePredicate) {
  22465. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22466. }
  22467. // Meshes
  22468. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22469. _this._processPointerMove(pickResult, evt);
  22470. };
  22471. this._onPointerDown = function (evt) {
  22472. _this._totalPointersPressed++;
  22473. _this._pickedDownMesh = null;
  22474. _this._meshPickProceed = false;
  22475. _this._updatePointerPosition(evt);
  22476. if (_this.preventDefaultOnPointerDown && canvas) {
  22477. evt.preventDefault();
  22478. canvas.focus();
  22479. }
  22480. // PreObservable support
  22481. if (_this.onPrePointerObservable.hasObservers()) {
  22482. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22483. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22484. _this.onPrePointerObservable.notifyObservers(pi, type);
  22485. if (pi.skipOnPointerObservable) {
  22486. return;
  22487. }
  22488. }
  22489. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22490. return;
  22491. }
  22492. _this._startingPointerPosition.x = _this._pointerX;
  22493. _this._startingPointerPosition.y = _this._pointerY;
  22494. _this._startingPointerTime = new Date().getTime();
  22495. if (!_this.pointerDownPredicate) {
  22496. _this.pointerDownPredicate = function (mesh) {
  22497. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22498. };
  22499. }
  22500. // Meshes
  22501. _this._pickedDownMesh = null;
  22502. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22503. _this._processPointerDown(pickResult, evt);
  22504. // Sprites
  22505. _this._pickedDownSprite = null;
  22506. if (_this.spriteManagers.length > 0) {
  22507. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22508. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22509. if (pickResult.pickedSprite.actionManager) {
  22510. _this._pickedDownSprite = pickResult.pickedSprite;
  22511. switch (evt.button) {
  22512. case 0:
  22513. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22514. break;
  22515. case 1:
  22516. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22517. break;
  22518. case 2:
  22519. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22520. break;
  22521. }
  22522. if (pickResult.pickedSprite.actionManager) {
  22523. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22524. }
  22525. }
  22526. }
  22527. }
  22528. };
  22529. this._onPointerUp = function (evt) {
  22530. if (_this._totalPointersPressed === 0) {
  22531. return; // So we need to test it the pointer down was pressed before.
  22532. }
  22533. _this._totalPointersPressed--;
  22534. _this._pickedUpMesh = null;
  22535. _this._meshPickProceed = false;
  22536. _this._updatePointerPosition(evt);
  22537. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22538. // PreObservable support
  22539. if (_this.onPrePointerObservable.hasObservers()) {
  22540. if (!clickInfo.ignore) {
  22541. if (!clickInfo.hasSwiped) {
  22542. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22543. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22544. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22545. _this.onPrePointerObservable.notifyObservers(pi, type);
  22546. if (pi.skipOnPointerObservable) {
  22547. return;
  22548. }
  22549. }
  22550. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22551. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  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. }
  22559. }
  22560. else {
  22561. var type = BABYLON.PointerEventTypes.POINTERUP;
  22562. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22563. _this.onPrePointerObservable.notifyObservers(pi, type);
  22564. if (pi.skipOnPointerObservable) {
  22565. return;
  22566. }
  22567. }
  22568. }
  22569. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22570. return;
  22571. }
  22572. if (!_this.pointerUpPredicate) {
  22573. _this.pointerUpPredicate = function (mesh) {
  22574. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22575. };
  22576. }
  22577. // Meshes
  22578. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22579. _this._initActionManager(null, clickInfo);
  22580. }
  22581. if (!pickResult) {
  22582. pickResult = _this._currentPickResult;
  22583. }
  22584. _this._processPointerUp(pickResult, evt, clickInfo);
  22585. // Sprites
  22586. if (_this.spriteManagers.length > 0) {
  22587. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22588. if (spritePickResult) {
  22589. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22590. if (spritePickResult.pickedSprite.actionManager) {
  22591. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22592. if (spritePickResult.pickedSprite.actionManager) {
  22593. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22594. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22595. }
  22596. }
  22597. }
  22598. }
  22599. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22600. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22601. }
  22602. }
  22603. }
  22604. _this._previousPickResult = _this._currentPickResult;
  22605. });
  22606. };
  22607. this._onKeyDown = function (evt) {
  22608. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22609. if (_this.onPreKeyboardObservable.hasObservers()) {
  22610. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22611. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22612. if (pi.skipOnPointerObservable) {
  22613. return;
  22614. }
  22615. }
  22616. if (_this.onKeyboardObservable.hasObservers()) {
  22617. var pi = new BABYLON.KeyboardInfo(type, evt);
  22618. _this.onKeyboardObservable.notifyObservers(pi, type);
  22619. }
  22620. if (_this.actionManager) {
  22621. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22622. }
  22623. };
  22624. this._onKeyUp = function (evt) {
  22625. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22626. if (_this.onPreKeyboardObservable.hasObservers()) {
  22627. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22628. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22629. if (pi.skipOnPointerObservable) {
  22630. return;
  22631. }
  22632. }
  22633. if (_this.onKeyboardObservable.hasObservers()) {
  22634. var pi = new BABYLON.KeyboardInfo(type, evt);
  22635. _this.onKeyboardObservable.notifyObservers(pi, type);
  22636. }
  22637. if (_this.actionManager) {
  22638. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22639. }
  22640. };
  22641. var engine = this.getEngine();
  22642. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22643. if (!canvas) {
  22644. return;
  22645. }
  22646. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22647. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22648. });
  22649. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22650. if (!canvas) {
  22651. return;
  22652. }
  22653. canvas.removeEventListener("keydown", _this._onKeyDown);
  22654. canvas.removeEventListener("keyup", _this._onKeyUp);
  22655. });
  22656. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22657. var canvas = this._engine.getRenderingCanvas();
  22658. if (!canvas) {
  22659. return;
  22660. }
  22661. if (attachMove) {
  22662. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22663. // Wheel
  22664. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22665. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22666. }
  22667. if (attachDown) {
  22668. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22669. }
  22670. if (attachUp) {
  22671. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22672. }
  22673. canvas.tabIndex = 1;
  22674. };
  22675. Scene.prototype.detachControl = function () {
  22676. var engine = this.getEngine();
  22677. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22678. var canvas = engine.getRenderingCanvas();
  22679. if (!canvas) {
  22680. return;
  22681. }
  22682. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22683. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22684. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22685. if (this._onCanvasBlurObserver) {
  22686. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22687. }
  22688. if (this._onCanvasFocusObserver) {
  22689. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22690. }
  22691. // Wheel
  22692. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22693. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22694. // Keyboard
  22695. canvas.removeEventListener("keydown", this._onKeyDown);
  22696. canvas.removeEventListener("keyup", this._onKeyUp);
  22697. // Observables
  22698. this.onKeyboardObservable.clear();
  22699. this.onPreKeyboardObservable.clear();
  22700. this.onPointerObservable.clear();
  22701. this.onPrePointerObservable.clear();
  22702. };
  22703. /**
  22704. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22705. * Delay loaded resources are not taking in account
  22706. * @return true if all required resources are ready
  22707. */
  22708. Scene.prototype.isReady = function () {
  22709. if (this._isDisposed) {
  22710. return false;
  22711. }
  22712. if (this._pendingData.length > 0) {
  22713. return false;
  22714. }
  22715. var index;
  22716. var engine = this.getEngine();
  22717. // Geometries
  22718. for (index = 0; index < this._geometries.length; index++) {
  22719. var geometry = this._geometries[index];
  22720. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22721. return false;
  22722. }
  22723. }
  22724. // Meshes
  22725. for (index = 0; index < this.meshes.length; index++) {
  22726. var mesh = this.meshes[index];
  22727. if (!mesh.isEnabled()) {
  22728. continue;
  22729. }
  22730. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22731. continue;
  22732. }
  22733. if (!mesh.isReady(true)) {
  22734. return false;
  22735. }
  22736. // Effect layers
  22737. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22738. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22739. var layer = _a[_i];
  22740. if (!layer.hasMesh(mesh)) {
  22741. continue;
  22742. }
  22743. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22744. var subMesh = _c[_b];
  22745. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22746. return false;
  22747. }
  22748. }
  22749. }
  22750. }
  22751. return true;
  22752. };
  22753. Scene.prototype.resetCachedMaterial = function () {
  22754. this._cachedMaterial = null;
  22755. this._cachedEffect = null;
  22756. this._cachedVisibility = null;
  22757. };
  22758. Scene.prototype.registerBeforeRender = function (func) {
  22759. this.onBeforeRenderObservable.add(func);
  22760. };
  22761. Scene.prototype.unregisterBeforeRender = function (func) {
  22762. this.onBeforeRenderObservable.removeCallback(func);
  22763. };
  22764. Scene.prototype.registerAfterRender = function (func) {
  22765. this.onAfterRenderObservable.add(func);
  22766. };
  22767. Scene.prototype.unregisterAfterRender = function (func) {
  22768. this.onAfterRenderObservable.removeCallback(func);
  22769. };
  22770. Scene.prototype._executeOnceBeforeRender = function (func) {
  22771. var _this = this;
  22772. var execFunc = function () {
  22773. func();
  22774. setTimeout(function () {
  22775. _this.unregisterBeforeRender(execFunc);
  22776. });
  22777. };
  22778. this.registerBeforeRender(execFunc);
  22779. };
  22780. /**
  22781. * The provided function will run before render once and will be disposed afterwards.
  22782. * A timeout delay can be provided so that the function will be executed in N ms.
  22783. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22784. * @param func The function to be executed.
  22785. * @param timeout optional delay in ms
  22786. */
  22787. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22788. var _this = this;
  22789. if (timeout !== undefined) {
  22790. setTimeout(function () {
  22791. _this._executeOnceBeforeRender(func);
  22792. }, timeout);
  22793. }
  22794. else {
  22795. this._executeOnceBeforeRender(func);
  22796. }
  22797. };
  22798. Scene.prototype._addPendingData = function (data) {
  22799. this._pendingData.push(data);
  22800. };
  22801. Scene.prototype._removePendingData = function (data) {
  22802. var wasLoading = this.isLoading;
  22803. var index = this._pendingData.indexOf(data);
  22804. if (index !== -1) {
  22805. this._pendingData.splice(index, 1);
  22806. }
  22807. if (wasLoading && !this.isLoading) {
  22808. this.onDataLoadedObservable.notifyObservers(this);
  22809. }
  22810. };
  22811. Scene.prototype.getWaitingItemsCount = function () {
  22812. return this._pendingData.length;
  22813. };
  22814. Object.defineProperty(Scene.prototype, "isLoading", {
  22815. get: function () {
  22816. return this._pendingData.length > 0;
  22817. },
  22818. enumerable: true,
  22819. configurable: true
  22820. });
  22821. /**
  22822. * Registers a function to be executed when the scene is ready.
  22823. * @param {Function} func - the function to be executed.
  22824. */
  22825. Scene.prototype.executeWhenReady = function (func) {
  22826. var _this = this;
  22827. this.onReadyObservable.add(func);
  22828. if (this._executeWhenReadyTimeoutId !== -1) {
  22829. return;
  22830. }
  22831. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22832. _this._checkIsReady();
  22833. }, 150);
  22834. };
  22835. /**
  22836. * Returns a promise that resolves when the scene is ready.
  22837. * @returns A promise that resolves when the scene is ready.
  22838. */
  22839. Scene.prototype.whenReadyAsync = function () {
  22840. var _this = this;
  22841. return new Promise(function (resolve) {
  22842. _this.executeWhenReady(function () {
  22843. resolve();
  22844. });
  22845. });
  22846. };
  22847. Scene.prototype._checkIsReady = function () {
  22848. var _this = this;
  22849. if (this.isReady()) {
  22850. this.onReadyObservable.notifyObservers(this);
  22851. this.onReadyObservable.clear();
  22852. this._executeWhenReadyTimeoutId = -1;
  22853. return;
  22854. }
  22855. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22856. _this._checkIsReady();
  22857. }, 150);
  22858. };
  22859. // Animations
  22860. /**
  22861. * Will start the animation sequence of a given target
  22862. * @param target - the target
  22863. * @param {number} from - from which frame should animation start
  22864. * @param {number} to - till which frame should animation run.
  22865. * @param {boolean} [loop] - should the animation loop
  22866. * @param {number} [speedRatio] - the speed in which to run the animation
  22867. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22868. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22869. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22870. * See BABYLON.Animatable
  22871. */
  22872. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22873. if (speedRatio === void 0) { speedRatio = 1.0; }
  22874. if (from > to && speedRatio > 0) {
  22875. speedRatio *= -1;
  22876. }
  22877. this.stopAnimation(target);
  22878. if (!animatable) {
  22879. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22880. }
  22881. // Local animations
  22882. if (target.animations) {
  22883. animatable.appendAnimations(target, target.animations);
  22884. }
  22885. // Children animations
  22886. if (target.getAnimatables) {
  22887. var animatables = target.getAnimatables();
  22888. for (var index = 0; index < animatables.length; index++) {
  22889. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22890. }
  22891. }
  22892. animatable.reset();
  22893. return animatable;
  22894. };
  22895. /**
  22896. * Begin a new animation on a given node
  22897. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22898. * @param {BABYLON.Animation[]} defines the list of animations to start
  22899. * @param {number} from defines the initial value
  22900. * @param {number} to defines the final value
  22901. * @param {boolean} loop defines if you want animation to loop (off by default)
  22902. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22903. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22904. * @returns the list of created animatables
  22905. */
  22906. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22907. if (speedRatio === undefined) {
  22908. speedRatio = 1.0;
  22909. }
  22910. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22911. return animatable;
  22912. };
  22913. /**
  22914. * Begin a new animation on a given node and its hierarchy
  22915. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22916. * @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.
  22917. * @param {BABYLON.Animation[]} defines the list of animations to start
  22918. * @param {number} from defines the initial value
  22919. * @param {number} to defines the final value
  22920. * @param {boolean} loop defines if you want animation to loop (off by default)
  22921. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22922. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22923. * @returns the list of animatables created for all nodes
  22924. */
  22925. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22926. var children = target.getDescendants(directDescendantsOnly);
  22927. var result = [];
  22928. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22929. var child = children_1[_i];
  22930. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22931. }
  22932. return result;
  22933. };
  22934. Scene.prototype.getAnimatableByTarget = function (target) {
  22935. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22936. if (this._activeAnimatables[index].target === target) {
  22937. return this._activeAnimatables[index];
  22938. }
  22939. }
  22940. return null;
  22941. };
  22942. Object.defineProperty(Scene.prototype, "animatables", {
  22943. get: function () {
  22944. return this._activeAnimatables;
  22945. },
  22946. enumerable: true,
  22947. configurable: true
  22948. });
  22949. /**
  22950. * Will stop the animation of the given target
  22951. * @param target - the target
  22952. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22953. * @see beginAnimation
  22954. */
  22955. Scene.prototype.stopAnimation = function (target, animationName) {
  22956. var animatable = this.getAnimatableByTarget(target);
  22957. if (animatable) {
  22958. animatable.stop(animationName);
  22959. }
  22960. };
  22961. /**
  22962. * Stops and removes all animations that have been applied to the scene
  22963. */
  22964. Scene.prototype.stopAllAnimations = function () {
  22965. if (this._activeAnimatables) {
  22966. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22967. this._activeAnimatables[i].stop();
  22968. }
  22969. this._activeAnimatables = [];
  22970. }
  22971. };
  22972. Scene.prototype._animate = function () {
  22973. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22974. return;
  22975. }
  22976. // Getting time
  22977. var now = BABYLON.Tools.Now;
  22978. if (!this._animationTimeLast) {
  22979. if (this._pendingData.length > 0) {
  22980. return;
  22981. }
  22982. this._animationTimeLast = now;
  22983. }
  22984. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22985. this._animationTime += deltaTime;
  22986. this._animationTimeLast = now;
  22987. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22988. this._activeAnimatables[index]._animate(this._animationTime);
  22989. }
  22990. };
  22991. // Matrix
  22992. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22993. this._useAlternateCameraConfiguration = active;
  22994. };
  22995. Scene.prototype.getViewMatrix = function () {
  22996. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22997. };
  22998. Scene.prototype.getProjectionMatrix = function () {
  22999. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23000. };
  23001. Scene.prototype.getTransformMatrix = function () {
  23002. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23003. };
  23004. Scene.prototype.setTransformMatrix = function (view, projection) {
  23005. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23006. return;
  23007. }
  23008. this._viewUpdateFlag = view.updateFlag;
  23009. this._projectionUpdateFlag = projection.updateFlag;
  23010. this._viewMatrix = view;
  23011. this._projectionMatrix = projection;
  23012. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23013. // Update frustum
  23014. if (!this._frustumPlanes) {
  23015. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23016. }
  23017. else {
  23018. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23019. }
  23020. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23021. var otherCamera = this.activeCamera._alternateCamera;
  23022. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23023. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23024. }
  23025. if (this._sceneUbo.useUbo) {
  23026. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23027. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23028. this._sceneUbo.update();
  23029. }
  23030. };
  23031. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23032. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23033. return;
  23034. }
  23035. this._alternateViewUpdateFlag = view.updateFlag;
  23036. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23037. this._alternateViewMatrix = view;
  23038. this._alternateProjectionMatrix = projection;
  23039. if (!this._alternateTransformMatrix) {
  23040. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23041. }
  23042. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23043. if (!this._alternateSceneUbo) {
  23044. this._createAlternateUbo();
  23045. }
  23046. if (this._alternateSceneUbo.useUbo) {
  23047. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23048. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23049. this._alternateSceneUbo.update();
  23050. }
  23051. };
  23052. Scene.prototype.getSceneUniformBuffer = function () {
  23053. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23054. };
  23055. // Methods
  23056. Scene.prototype.getUniqueId = function () {
  23057. var result = Scene._uniqueIdCounter;
  23058. Scene._uniqueIdCounter++;
  23059. return result;
  23060. };
  23061. Scene.prototype.addMesh = function (newMesh) {
  23062. this.meshes.push(newMesh);
  23063. //notify the collision coordinator
  23064. if (this.collisionCoordinator) {
  23065. this.collisionCoordinator.onMeshAdded(newMesh);
  23066. }
  23067. newMesh._resyncLightSources();
  23068. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23069. };
  23070. Scene.prototype.removeMesh = function (toRemove) {
  23071. var index = this.meshes.indexOf(toRemove);
  23072. if (index !== -1) {
  23073. // Remove from the scene if mesh found
  23074. this.meshes.splice(index, 1);
  23075. }
  23076. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23077. return index;
  23078. };
  23079. Scene.prototype.addTransformNode = function (newTransformNode) {
  23080. this.transformNodes.push(newTransformNode);
  23081. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23082. };
  23083. Scene.prototype.removeTransformNode = function (toRemove) {
  23084. var index = this.transformNodes.indexOf(toRemove);
  23085. if (index !== -1) {
  23086. // Remove from the scene if found
  23087. this.transformNodes.splice(index, 1);
  23088. }
  23089. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23090. return index;
  23091. };
  23092. Scene.prototype.removeSkeleton = function (toRemove) {
  23093. var index = this.skeletons.indexOf(toRemove);
  23094. if (index !== -1) {
  23095. // Remove from the scene if found
  23096. this.skeletons.splice(index, 1);
  23097. }
  23098. return index;
  23099. };
  23100. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23101. var index = this.morphTargetManagers.indexOf(toRemove);
  23102. if (index !== -1) {
  23103. // Remove from the scene if found
  23104. this.morphTargetManagers.splice(index, 1);
  23105. }
  23106. return index;
  23107. };
  23108. Scene.prototype.removeLight = function (toRemove) {
  23109. var index = this.lights.indexOf(toRemove);
  23110. if (index !== -1) {
  23111. // Remove from meshes
  23112. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23113. var mesh = _a[_i];
  23114. mesh._removeLightSource(toRemove);
  23115. }
  23116. // Remove from the scene if mesh found
  23117. this.lights.splice(index, 1);
  23118. this.sortLightsByPriority();
  23119. }
  23120. this.onLightRemovedObservable.notifyObservers(toRemove);
  23121. return index;
  23122. };
  23123. Scene.prototype.removeCamera = function (toRemove) {
  23124. var index = this.cameras.indexOf(toRemove);
  23125. if (index !== -1) {
  23126. // Remove from the scene if mesh found
  23127. this.cameras.splice(index, 1);
  23128. }
  23129. // Remove from activeCameras
  23130. var index2 = this.activeCameras.indexOf(toRemove);
  23131. if (index2 !== -1) {
  23132. // Remove from the scene if mesh found
  23133. this.activeCameras.splice(index2, 1);
  23134. }
  23135. // Reset the activeCamera
  23136. if (this.activeCamera === toRemove) {
  23137. if (this.cameras.length > 0) {
  23138. this.activeCamera = this.cameras[0];
  23139. }
  23140. else {
  23141. this.activeCamera = null;
  23142. }
  23143. }
  23144. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23145. return index;
  23146. };
  23147. Scene.prototype.removeParticleSystem = function (toRemove) {
  23148. var index = this.particleSystems.indexOf(toRemove);
  23149. if (index !== -1) {
  23150. this.particleSystems.splice(index, 1);
  23151. }
  23152. return index;
  23153. };
  23154. ;
  23155. Scene.prototype.removeAnimation = function (toRemove) {
  23156. var index = this.animations.indexOf(toRemove);
  23157. if (index !== -1) {
  23158. this.animations.splice(index, 1);
  23159. }
  23160. return index;
  23161. };
  23162. ;
  23163. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23164. var index = this.multiMaterials.indexOf(toRemove);
  23165. if (index !== -1) {
  23166. this.multiMaterials.splice(index, 1);
  23167. }
  23168. return index;
  23169. };
  23170. ;
  23171. Scene.prototype.removeMaterial = function (toRemove) {
  23172. var index = this.materials.indexOf(toRemove);
  23173. if (index !== -1) {
  23174. this.materials.splice(index, 1);
  23175. }
  23176. return index;
  23177. };
  23178. ;
  23179. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23180. var index = this.lensFlareSystems.indexOf(toRemove);
  23181. if (index !== -1) {
  23182. this.lensFlareSystems.splice(index, 1);
  23183. }
  23184. return index;
  23185. };
  23186. ;
  23187. Scene.prototype.removeActionManager = function (toRemove) {
  23188. var index = this._actionManagers.indexOf(toRemove);
  23189. if (index !== -1) {
  23190. this._actionManagers.splice(index, 1);
  23191. }
  23192. return index;
  23193. };
  23194. ;
  23195. Scene.prototype.addLight = function (newLight) {
  23196. this.lights.push(newLight);
  23197. this.sortLightsByPriority();
  23198. // Add light to all meshes (To support if the light is removed and then readded)
  23199. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23200. var mesh = _a[_i];
  23201. if (mesh._lightSources.indexOf(newLight) === -1) {
  23202. mesh._lightSources.push(newLight);
  23203. mesh._resyncLightSources();
  23204. }
  23205. }
  23206. this.onNewLightAddedObservable.notifyObservers(newLight);
  23207. };
  23208. Scene.prototype.sortLightsByPriority = function () {
  23209. if (this.requireLightSorting) {
  23210. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23211. }
  23212. };
  23213. Scene.prototype.addCamera = function (newCamera) {
  23214. this.cameras.push(newCamera);
  23215. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23216. };
  23217. Scene.prototype.addSkeleton = function (newSkeleton) {
  23218. this.skeletons.push(newSkeleton);
  23219. };
  23220. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23221. this.particleSystems.push(newParticleSystem);
  23222. };
  23223. Scene.prototype.addAnimation = function (newAnimation) {
  23224. this.animations.push(newAnimation);
  23225. };
  23226. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23227. this.multiMaterials.push(newMultiMaterial);
  23228. };
  23229. Scene.prototype.addMaterial = function (newMaterial) {
  23230. this.materials.push(newMaterial);
  23231. };
  23232. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23233. this.morphTargetManagers.push(newMorphTargetManager);
  23234. };
  23235. Scene.prototype.addGeometry = function (newGeometrie) {
  23236. this._geometries.push(newGeometrie);
  23237. };
  23238. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23239. this.lensFlareSystems.push(newLensFlareSystem);
  23240. };
  23241. Scene.prototype.addActionManager = function (newActionManager) {
  23242. this._actionManagers.push(newActionManager);
  23243. };
  23244. /**
  23245. * Switch active camera
  23246. * @param {Camera} newCamera - new active camera
  23247. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23248. */
  23249. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23250. if (attachControl === void 0) { attachControl = true; }
  23251. var canvas = this._engine.getRenderingCanvas();
  23252. if (!canvas) {
  23253. return;
  23254. }
  23255. if (this.activeCamera) {
  23256. this.activeCamera.detachControl(canvas);
  23257. }
  23258. this.activeCamera = newCamera;
  23259. if (attachControl) {
  23260. newCamera.attachControl(canvas);
  23261. }
  23262. };
  23263. /**
  23264. * sets the active camera of the scene using its ID
  23265. * @param {string} id - the camera's ID
  23266. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23267. * @see activeCamera
  23268. */
  23269. Scene.prototype.setActiveCameraByID = function (id) {
  23270. var camera = this.getCameraByID(id);
  23271. if (camera) {
  23272. this.activeCamera = camera;
  23273. return camera;
  23274. }
  23275. return null;
  23276. };
  23277. /**
  23278. * sets the active camera of the scene using its name
  23279. * @param {string} name - the camera's name
  23280. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23281. * @see activeCamera
  23282. */
  23283. Scene.prototype.setActiveCameraByName = function (name) {
  23284. var camera = this.getCameraByName(name);
  23285. if (camera) {
  23286. this.activeCamera = camera;
  23287. return camera;
  23288. }
  23289. return null;
  23290. };
  23291. /**
  23292. * get an animation group using its name
  23293. * @param {string} the material's name
  23294. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23295. */
  23296. Scene.prototype.getAnimationGroupByName = function (name) {
  23297. for (var index = 0; index < this.animationGroups.length; index++) {
  23298. if (this.animationGroups[index].name === name) {
  23299. return this.animationGroups[index];
  23300. }
  23301. }
  23302. return null;
  23303. };
  23304. /**
  23305. * get a material using its id
  23306. * @param {string} the material's ID
  23307. * @return {BABYLON.Material|null} the material or null if none found.
  23308. */
  23309. Scene.prototype.getMaterialByID = function (id) {
  23310. for (var index = 0; index < this.materials.length; index++) {
  23311. if (this.materials[index].id === id) {
  23312. return this.materials[index];
  23313. }
  23314. }
  23315. return null;
  23316. };
  23317. /**
  23318. * get a material using its name
  23319. * @param {string} the material's name
  23320. * @return {BABYLON.Material|null} the material or null if none found.
  23321. */
  23322. Scene.prototype.getMaterialByName = function (name) {
  23323. for (var index = 0; index < this.materials.length; index++) {
  23324. if (this.materials[index].name === name) {
  23325. return this.materials[index];
  23326. }
  23327. }
  23328. return null;
  23329. };
  23330. Scene.prototype.getLensFlareSystemByName = function (name) {
  23331. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23332. if (this.lensFlareSystems[index].name === name) {
  23333. return this.lensFlareSystems[index];
  23334. }
  23335. }
  23336. return null;
  23337. };
  23338. Scene.prototype.getLensFlareSystemByID = function (id) {
  23339. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23340. if (this.lensFlareSystems[index].id === id) {
  23341. return this.lensFlareSystems[index];
  23342. }
  23343. }
  23344. return null;
  23345. };
  23346. Scene.prototype.getCameraByID = function (id) {
  23347. for (var index = 0; index < this.cameras.length; index++) {
  23348. if (this.cameras[index].id === id) {
  23349. return this.cameras[index];
  23350. }
  23351. }
  23352. return null;
  23353. };
  23354. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23355. for (var index = 0; index < this.cameras.length; index++) {
  23356. if (this.cameras[index].uniqueId === uniqueId) {
  23357. return this.cameras[index];
  23358. }
  23359. }
  23360. return null;
  23361. };
  23362. /**
  23363. * get a camera using its name
  23364. * @param {string} the camera's name
  23365. * @return {BABYLON.Camera|null} the camera or null if none found.
  23366. */
  23367. Scene.prototype.getCameraByName = function (name) {
  23368. for (var index = 0; index < this.cameras.length; index++) {
  23369. if (this.cameras[index].name === name) {
  23370. return this.cameras[index];
  23371. }
  23372. }
  23373. return null;
  23374. };
  23375. /**
  23376. * get a bone using its id
  23377. * @param {string} the bone's id
  23378. * @return {BABYLON.Bone|null} the bone or null if not found
  23379. */
  23380. Scene.prototype.getBoneByID = function (id) {
  23381. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23382. var skeleton = this.skeletons[skeletonIndex];
  23383. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23384. if (skeleton.bones[boneIndex].id === id) {
  23385. return skeleton.bones[boneIndex];
  23386. }
  23387. }
  23388. }
  23389. return null;
  23390. };
  23391. /**
  23392. * get a bone using its id
  23393. * @param {string} the bone's name
  23394. * @return {BABYLON.Bone|null} the bone or null if not found
  23395. */
  23396. Scene.prototype.getBoneByName = function (name) {
  23397. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23398. var skeleton = this.skeletons[skeletonIndex];
  23399. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23400. if (skeleton.bones[boneIndex].name === name) {
  23401. return skeleton.bones[boneIndex];
  23402. }
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. /**
  23408. * get a light node using its name
  23409. * @param {string} the light's name
  23410. * @return {BABYLON.Light|null} the light or null if none found.
  23411. */
  23412. Scene.prototype.getLightByName = function (name) {
  23413. for (var index = 0; index < this.lights.length; index++) {
  23414. if (this.lights[index].name === name) {
  23415. return this.lights[index];
  23416. }
  23417. }
  23418. return null;
  23419. };
  23420. /**
  23421. * get a light node using its ID
  23422. * @param {string} the light's id
  23423. * @return {BABYLON.Light|null} the light or null if none found.
  23424. */
  23425. Scene.prototype.getLightByID = function (id) {
  23426. for (var index = 0; index < this.lights.length; index++) {
  23427. if (this.lights[index].id === id) {
  23428. return this.lights[index];
  23429. }
  23430. }
  23431. return null;
  23432. };
  23433. /**
  23434. * get a light node using its scene-generated unique ID
  23435. * @param {number} the light's unique id
  23436. * @return {BABYLON.Light|null} the light or null if none found.
  23437. */
  23438. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23439. for (var index = 0; index < this.lights.length; index++) {
  23440. if (this.lights[index].uniqueId === uniqueId) {
  23441. return this.lights[index];
  23442. }
  23443. }
  23444. return null;
  23445. };
  23446. /**
  23447. * get a particle system by id
  23448. * @param id {number} the particle system id
  23449. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23450. */
  23451. Scene.prototype.getParticleSystemByID = function (id) {
  23452. for (var index = 0; index < this.particleSystems.length; index++) {
  23453. if (this.particleSystems[index].id === id) {
  23454. return this.particleSystems[index];
  23455. }
  23456. }
  23457. return null;
  23458. };
  23459. /**
  23460. * get a geometry using its ID
  23461. * @param {string} the geometry's id
  23462. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23463. */
  23464. Scene.prototype.getGeometryByID = function (id) {
  23465. for (var index = 0; index < this._geometries.length; index++) {
  23466. if (this._geometries[index].id === id) {
  23467. return this._geometries[index];
  23468. }
  23469. }
  23470. return null;
  23471. };
  23472. /**
  23473. * add a new geometry to this scene.
  23474. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23475. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23476. * @return {boolean} was the geometry added or not
  23477. */
  23478. Scene.prototype.pushGeometry = function (geometry, force) {
  23479. if (!force && this.getGeometryByID(geometry.id)) {
  23480. return false;
  23481. }
  23482. this._geometries.push(geometry);
  23483. //notify the collision coordinator
  23484. if (this.collisionCoordinator) {
  23485. this.collisionCoordinator.onGeometryAdded(geometry);
  23486. }
  23487. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23488. return true;
  23489. };
  23490. /**
  23491. * Removes an existing geometry
  23492. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23493. * @return {boolean} was the geometry removed or not
  23494. */
  23495. Scene.prototype.removeGeometry = function (geometry) {
  23496. var index = this._geometries.indexOf(geometry);
  23497. if (index > -1) {
  23498. this._geometries.splice(index, 1);
  23499. //notify the collision coordinator
  23500. if (this.collisionCoordinator) {
  23501. this.collisionCoordinator.onGeometryDeleted(geometry);
  23502. }
  23503. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23504. return true;
  23505. }
  23506. return false;
  23507. };
  23508. Scene.prototype.getGeometries = function () {
  23509. return this._geometries;
  23510. };
  23511. /**
  23512. * Get the first added mesh found of a given ID
  23513. * @param {string} id - the id to search for
  23514. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23515. */
  23516. Scene.prototype.getMeshByID = function (id) {
  23517. for (var index = 0; index < this.meshes.length; index++) {
  23518. if (this.meshes[index].id === id) {
  23519. return this.meshes[index];
  23520. }
  23521. }
  23522. return null;
  23523. };
  23524. Scene.prototype.getMeshesByID = function (id) {
  23525. return this.meshes.filter(function (m) {
  23526. return m.id === id;
  23527. });
  23528. };
  23529. /**
  23530. * Get the first added transform node found of a given ID
  23531. * @param {string} id - the id to search for
  23532. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23533. */
  23534. Scene.prototype.getTransformNodeByID = function (id) {
  23535. for (var index = 0; index < this.transformNodes.length; index++) {
  23536. if (this.transformNodes[index].id === id) {
  23537. return this.transformNodes[index];
  23538. }
  23539. }
  23540. return null;
  23541. };
  23542. Scene.prototype.getTransformNodesByID = function (id) {
  23543. return this.transformNodes.filter(function (m) {
  23544. return m.id === id;
  23545. });
  23546. };
  23547. /**
  23548. * Get a mesh with its auto-generated unique id
  23549. * @param {number} uniqueId - the unique id to search for
  23550. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23551. */
  23552. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23553. for (var index = 0; index < this.meshes.length; index++) {
  23554. if (this.meshes[index].uniqueId === uniqueId) {
  23555. return this.meshes[index];
  23556. }
  23557. }
  23558. return null;
  23559. };
  23560. /**
  23561. * Get a the last added mesh found of a given ID
  23562. * @param {string} id - the id to search for
  23563. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23564. */
  23565. Scene.prototype.getLastMeshByID = function (id) {
  23566. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23567. if (this.meshes[index].id === id) {
  23568. return this.meshes[index];
  23569. }
  23570. }
  23571. return null;
  23572. };
  23573. /**
  23574. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23575. * @param {string} id - the id to search for
  23576. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23577. */
  23578. Scene.prototype.getLastEntryByID = function (id) {
  23579. var index;
  23580. for (index = this.meshes.length - 1; index >= 0; index--) {
  23581. if (this.meshes[index].id === id) {
  23582. return this.meshes[index];
  23583. }
  23584. }
  23585. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23586. if (this.transformNodes[index].id === id) {
  23587. return this.transformNodes[index];
  23588. }
  23589. }
  23590. for (index = this.cameras.length - 1; index >= 0; index--) {
  23591. if (this.cameras[index].id === id) {
  23592. return this.cameras[index];
  23593. }
  23594. }
  23595. for (index = this.lights.length - 1; index >= 0; index--) {
  23596. if (this.lights[index].id === id) {
  23597. return this.lights[index];
  23598. }
  23599. }
  23600. return null;
  23601. };
  23602. Scene.prototype.getNodeByID = function (id) {
  23603. var mesh = this.getMeshByID(id);
  23604. if (mesh) {
  23605. return mesh;
  23606. }
  23607. var light = this.getLightByID(id);
  23608. if (light) {
  23609. return light;
  23610. }
  23611. var camera = this.getCameraByID(id);
  23612. if (camera) {
  23613. return camera;
  23614. }
  23615. var bone = this.getBoneByID(id);
  23616. return bone;
  23617. };
  23618. Scene.prototype.getNodeByName = function (name) {
  23619. var mesh = this.getMeshByName(name);
  23620. if (mesh) {
  23621. return mesh;
  23622. }
  23623. var light = this.getLightByName(name);
  23624. if (light) {
  23625. return light;
  23626. }
  23627. var camera = this.getCameraByName(name);
  23628. if (camera) {
  23629. return camera;
  23630. }
  23631. var bone = this.getBoneByName(name);
  23632. return bone;
  23633. };
  23634. Scene.prototype.getMeshByName = function (name) {
  23635. for (var index = 0; index < this.meshes.length; index++) {
  23636. if (this.meshes[index].name === name) {
  23637. return this.meshes[index];
  23638. }
  23639. }
  23640. return null;
  23641. };
  23642. Scene.prototype.getTransformNodeByName = function (name) {
  23643. for (var index = 0; index < this.transformNodes.length; index++) {
  23644. if (this.transformNodes[index].name === name) {
  23645. return this.transformNodes[index];
  23646. }
  23647. }
  23648. return null;
  23649. };
  23650. Scene.prototype.getSoundByName = function (name) {
  23651. var index;
  23652. if (BABYLON.AudioEngine) {
  23653. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23654. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23655. return this.mainSoundTrack.soundCollection[index];
  23656. }
  23657. }
  23658. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23659. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23660. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23661. return this.soundTracks[sdIndex].soundCollection[index];
  23662. }
  23663. }
  23664. }
  23665. }
  23666. return null;
  23667. };
  23668. Scene.prototype.getLastSkeletonByID = function (id) {
  23669. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23670. if (this.skeletons[index].id === id) {
  23671. return this.skeletons[index];
  23672. }
  23673. }
  23674. return null;
  23675. };
  23676. Scene.prototype.getSkeletonById = function (id) {
  23677. for (var index = 0; index < this.skeletons.length; index++) {
  23678. if (this.skeletons[index].id === id) {
  23679. return this.skeletons[index];
  23680. }
  23681. }
  23682. return null;
  23683. };
  23684. Scene.prototype.getSkeletonByName = function (name) {
  23685. for (var index = 0; index < this.skeletons.length; index++) {
  23686. if (this.skeletons[index].name === name) {
  23687. return this.skeletons[index];
  23688. }
  23689. }
  23690. return null;
  23691. };
  23692. Scene.prototype.getMorphTargetManagerById = function (id) {
  23693. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23694. if (this.morphTargetManagers[index].uniqueId === id) {
  23695. return this.morphTargetManagers[index];
  23696. }
  23697. }
  23698. return null;
  23699. };
  23700. Scene.prototype.isActiveMesh = function (mesh) {
  23701. return (this._activeMeshes.indexOf(mesh) !== -1);
  23702. };
  23703. /**
  23704. * Return a the first highlight layer of the scene with a given name.
  23705. * @param name The name of the highlight layer to look for.
  23706. * @return The highlight layer if found otherwise null.
  23707. */
  23708. Scene.prototype.getHighlightLayerByName = function (name) {
  23709. for (var index = 0; index < this.effectLayers.length; index++) {
  23710. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23711. return this.effectLayers[index];
  23712. }
  23713. }
  23714. return null;
  23715. };
  23716. /**
  23717. * Return a the first highlight layer of the scene with a given name.
  23718. * @param name The name of the highlight layer to look for.
  23719. * @return The highlight layer if found otherwise null.
  23720. */
  23721. Scene.prototype.getGlowLayerByName = function (name) {
  23722. for (var index = 0; index < this.effectLayers.length; index++) {
  23723. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23724. return this.effectLayers[index];
  23725. }
  23726. }
  23727. return null;
  23728. };
  23729. Object.defineProperty(Scene.prototype, "uid", {
  23730. /**
  23731. * Return a unique id as a string which can serve as an identifier for the scene
  23732. */
  23733. get: function () {
  23734. if (!this._uid) {
  23735. this._uid = BABYLON.Tools.RandomId();
  23736. }
  23737. return this._uid;
  23738. },
  23739. enumerable: true,
  23740. configurable: true
  23741. });
  23742. /**
  23743. * Add an externaly attached data from its key.
  23744. * This method call will fail and return false, if such key already exists.
  23745. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23746. * @param key the unique key that identifies the data
  23747. * @param data the data object to associate to the key for this Engine instance
  23748. * @return true if no such key were already present and the data was added successfully, false otherwise
  23749. */
  23750. Scene.prototype.addExternalData = function (key, data) {
  23751. if (!this._externalData) {
  23752. this._externalData = new BABYLON.StringDictionary();
  23753. }
  23754. return this._externalData.add(key, data);
  23755. };
  23756. /**
  23757. * Get an externaly attached data from its key
  23758. * @param key the unique key that identifies the data
  23759. * @return the associated data, if present (can be null), or undefined if not present
  23760. */
  23761. Scene.prototype.getExternalData = function (key) {
  23762. if (!this._externalData) {
  23763. return null;
  23764. }
  23765. return this._externalData.get(key);
  23766. };
  23767. /**
  23768. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23769. * @param key the unique key that identifies the data
  23770. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23771. * @return the associated data, can be null if the factory returned null.
  23772. */
  23773. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23774. if (!this._externalData) {
  23775. this._externalData = new BABYLON.StringDictionary();
  23776. }
  23777. return this._externalData.getOrAddWithFactory(key, factory);
  23778. };
  23779. /**
  23780. * Remove an externaly attached data from the Engine instance
  23781. * @param key the unique key that identifies the data
  23782. * @return true if the data was successfully removed, false if it doesn't exist
  23783. */
  23784. Scene.prototype.removeExternalData = function (key) {
  23785. return this._externalData.remove(key);
  23786. };
  23787. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23788. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23789. if (mesh.showSubMeshesBoundingBox) {
  23790. var boundingInfo = subMesh.getBoundingInfo();
  23791. if (boundingInfo !== null && boundingInfo !== undefined) {
  23792. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23793. }
  23794. }
  23795. var material = subMesh.getMaterial();
  23796. if (material !== null && material !== undefined) {
  23797. // Render targets
  23798. if (material.getRenderTargetTextures !== undefined) {
  23799. if (this._processedMaterials.indexOf(material) === -1) {
  23800. this._processedMaterials.push(material);
  23801. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23802. }
  23803. }
  23804. // Dispatch
  23805. this._activeIndices.addCount(subMesh.indexCount, false);
  23806. this._renderingManager.dispatch(subMesh, mesh, material);
  23807. }
  23808. }
  23809. };
  23810. Scene.prototype._isInIntermediateRendering = function () {
  23811. return this._intermediateRendering;
  23812. };
  23813. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23814. this._activeMeshCandidateProvider = provider;
  23815. };
  23816. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23817. return this._activeMeshCandidateProvider;
  23818. };
  23819. /**
  23820. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23821. */
  23822. Scene.prototype.freezeActiveMeshes = function () {
  23823. this._evaluateActiveMeshes();
  23824. this._activeMeshesFrozen = true;
  23825. return this;
  23826. };
  23827. /**
  23828. * Use this function to restart evaluating active meshes on every frame
  23829. */
  23830. Scene.prototype.unfreezeActiveMeshes = function () {
  23831. this._activeMeshesFrozen = false;
  23832. return this;
  23833. };
  23834. Scene.prototype._evaluateActiveMeshes = function () {
  23835. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23836. return;
  23837. }
  23838. if (!this.activeCamera) {
  23839. return;
  23840. }
  23841. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23842. this.activeCamera._activeMeshes.reset();
  23843. this._activeMeshes.reset();
  23844. this._renderingManager.reset();
  23845. this._processedMaterials.reset();
  23846. this._activeParticleSystems.reset();
  23847. this._activeSkeletons.reset();
  23848. this._softwareSkinnedMeshes.reset();
  23849. if (this._boundingBoxRenderer) {
  23850. this._boundingBoxRenderer.reset();
  23851. }
  23852. // Meshes
  23853. var meshes;
  23854. var len;
  23855. var checkIsEnabled = true;
  23856. // Determine mesh candidates
  23857. if (this._activeMeshCandidateProvider !== undefined) {
  23858. // Use _activeMeshCandidateProvider
  23859. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23860. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23861. if (meshes !== undefined) {
  23862. len = meshes.length;
  23863. }
  23864. else {
  23865. len = 0;
  23866. }
  23867. }
  23868. else if (this._selectionOctree !== undefined) {
  23869. // Octree
  23870. var selection = this._selectionOctree.select(this._frustumPlanes);
  23871. meshes = selection.data;
  23872. len = selection.length;
  23873. }
  23874. else {
  23875. // Full scene traversal
  23876. len = this.meshes.length;
  23877. meshes = this.meshes;
  23878. }
  23879. // Check each mesh
  23880. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23881. mesh = meshes[meshIndex];
  23882. if (mesh.isBlocked) {
  23883. continue;
  23884. }
  23885. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23886. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23887. continue;
  23888. }
  23889. mesh.computeWorldMatrix();
  23890. // Intersections
  23891. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23892. this._meshesForIntersections.pushNoDuplicate(mesh);
  23893. }
  23894. // Switch to current LOD
  23895. meshLOD = mesh.getLOD(this.activeCamera);
  23896. if (meshLOD === undefined || meshLOD === null) {
  23897. continue;
  23898. }
  23899. mesh._preActivate();
  23900. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23901. this._activeMeshes.push(mesh);
  23902. this.activeCamera._activeMeshes.push(mesh);
  23903. mesh._activate(this._renderId);
  23904. if (meshLOD !== mesh) {
  23905. meshLOD._activate(this._renderId);
  23906. }
  23907. this._activeMesh(mesh, meshLOD);
  23908. }
  23909. }
  23910. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23911. // Particle systems
  23912. if (this.particlesEnabled) {
  23913. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23914. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23915. var particleSystem = this.particleSystems[particleIndex];
  23916. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23917. continue;
  23918. }
  23919. var emitter = particleSystem.emitter;
  23920. if (!emitter.position || emitter.isEnabled()) {
  23921. this._activeParticleSystems.push(particleSystem);
  23922. particleSystem.animate();
  23923. this._renderingManager.dispatchParticles(particleSystem);
  23924. }
  23925. }
  23926. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23927. }
  23928. };
  23929. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23930. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23931. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23932. mesh.skeleton.prepare();
  23933. }
  23934. if (!mesh.computeBonesUsingShaders) {
  23935. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23936. }
  23937. }
  23938. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23939. var boundingInfo = sourceMesh.getBoundingInfo();
  23940. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23941. }
  23942. if (mesh !== undefined && mesh !== null
  23943. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23944. // Submeshes Octrees
  23945. var len;
  23946. var subMeshes;
  23947. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23948. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23949. len = intersections.length;
  23950. subMeshes = intersections.data;
  23951. }
  23952. else {
  23953. subMeshes = mesh.subMeshes;
  23954. len = subMeshes.length;
  23955. }
  23956. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23957. subMesh = subMeshes[subIndex];
  23958. this._evaluateSubMesh(subMesh, mesh);
  23959. }
  23960. }
  23961. };
  23962. Scene.prototype.updateTransformMatrix = function (force) {
  23963. if (!this.activeCamera) {
  23964. return;
  23965. }
  23966. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23967. };
  23968. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23969. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23970. };
  23971. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23972. if (camera && camera._skipRendering) {
  23973. return;
  23974. }
  23975. var engine = this._engine;
  23976. this.activeCamera = camera;
  23977. if (!this.activeCamera)
  23978. throw new Error("Active camera not set");
  23979. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23980. // Viewport
  23981. engine.setViewport(this.activeCamera.viewport);
  23982. // Camera
  23983. this.resetCachedMaterial();
  23984. this._renderId++;
  23985. this.updateTransformMatrix();
  23986. if (camera._alternateCamera) {
  23987. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23988. this._alternateRendering = true;
  23989. }
  23990. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23991. // Meshes
  23992. this._evaluateActiveMeshes();
  23993. // Software skinning
  23994. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23995. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23996. mesh.applySkeleton(mesh.skeleton);
  23997. }
  23998. // Render targets
  23999. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24000. var needsRestoreFrameBuffer = false;
  24001. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24002. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24003. }
  24004. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24005. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24006. }
  24007. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24008. this._intermediateRendering = true;
  24009. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24010. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24011. var renderTarget = this._renderTargets.data[renderIndex];
  24012. if (renderTarget._shouldRender()) {
  24013. this._renderId++;
  24014. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24015. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24016. }
  24017. }
  24018. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24019. this._intermediateRendering = false;
  24020. this._renderId++;
  24021. needsRestoreFrameBuffer = true; // Restore back buffer
  24022. }
  24023. // Render EffecttLayer Texture
  24024. var stencilState = this._engine.getStencilBuffer();
  24025. var renderEffects = false;
  24026. var needStencil = false;
  24027. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24028. this._intermediateRendering = true;
  24029. for (var i = 0; i < this.effectLayers.length; i++) {
  24030. var effectLayer = this.effectLayers[i];
  24031. if (effectLayer.shouldRender() &&
  24032. (!effectLayer.camera ||
  24033. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24034. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24035. renderEffects = true;
  24036. needStencil = needStencil || effectLayer.needStencil();
  24037. var renderTarget = effectLayer._mainTexture;
  24038. if (renderTarget._shouldRender()) {
  24039. this._renderId++;
  24040. renderTarget.render(false, false);
  24041. needsRestoreFrameBuffer = true;
  24042. }
  24043. }
  24044. }
  24045. this._intermediateRendering = false;
  24046. this._renderId++;
  24047. }
  24048. if (needsRestoreFrameBuffer) {
  24049. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24050. }
  24051. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24052. // Prepare Frame
  24053. this.postProcessManager._prepareFrame();
  24054. // Backgrounds
  24055. var layerIndex;
  24056. var layer;
  24057. if (this.layers.length) {
  24058. engine.setDepthBuffer(false);
  24059. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24060. layer = this.layers[layerIndex];
  24061. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24062. layer.render();
  24063. }
  24064. }
  24065. engine.setDepthBuffer(true);
  24066. }
  24067. // Activate effect Layer stencil
  24068. if (needStencil) {
  24069. this._engine.setStencilBuffer(true);
  24070. }
  24071. // Render
  24072. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24073. this._renderingManager.render(null, null, true, true);
  24074. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24075. // Restore effect Layer stencil
  24076. if (needStencil) {
  24077. this._engine.setStencilBuffer(stencilState);
  24078. }
  24079. // Bounding boxes
  24080. if (this._boundingBoxRenderer) {
  24081. this._boundingBoxRenderer.render();
  24082. }
  24083. // Lens flares
  24084. if (this.lensFlaresEnabled) {
  24085. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24086. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24087. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24088. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24089. lensFlareSystem.render();
  24090. }
  24091. }
  24092. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24093. }
  24094. // Foregrounds
  24095. if (this.layers.length) {
  24096. engine.setDepthBuffer(false);
  24097. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24098. layer = this.layers[layerIndex];
  24099. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24100. layer.render();
  24101. }
  24102. }
  24103. engine.setDepthBuffer(true);
  24104. }
  24105. // Effect Layer
  24106. if (renderEffects) {
  24107. engine.setDepthBuffer(false);
  24108. for (var i = 0; i < this.effectLayers.length; i++) {
  24109. if (this.effectLayers[i].shouldRender()) {
  24110. this.effectLayers[i].render();
  24111. }
  24112. }
  24113. engine.setDepthBuffer(true);
  24114. }
  24115. // Finalize frame
  24116. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24117. // Reset some special arrays
  24118. this._renderTargets.reset();
  24119. this._alternateRendering = false;
  24120. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24121. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24122. };
  24123. Scene.prototype._processSubCameras = function (camera) {
  24124. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24125. this._renderForCamera(camera);
  24126. return;
  24127. }
  24128. // rig cameras
  24129. for (var index = 0; index < camera._rigCameras.length; index++) {
  24130. this._renderForCamera(camera._rigCameras[index], camera);
  24131. }
  24132. this.activeCamera = camera;
  24133. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24134. };
  24135. Scene.prototype._checkIntersections = function () {
  24136. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24137. var sourceMesh = this._meshesForIntersections.data[index];
  24138. if (!sourceMesh.actionManager) {
  24139. continue;
  24140. }
  24141. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24142. var action = sourceMesh.actionManager.actions[actionIndex];
  24143. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24144. var parameters = action.getTriggerParameter();
  24145. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24146. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24147. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24148. if (areIntersecting && currentIntersectionInProgress === -1) {
  24149. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24150. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24151. sourceMesh._intersectionsInProgress.push(otherMesh);
  24152. }
  24153. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24154. sourceMesh._intersectionsInProgress.push(otherMesh);
  24155. }
  24156. }
  24157. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24158. //They intersected, and now they don't.
  24159. //is this trigger an exit trigger? execute an event.
  24160. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24161. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24162. }
  24163. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24164. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24165. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24166. }
  24167. }
  24168. }
  24169. }
  24170. }
  24171. };
  24172. Scene.prototype.render = function () {
  24173. if (this.isDisposed) {
  24174. return;
  24175. }
  24176. this._activeParticles.fetchNewFrame();
  24177. this._totalVertices.fetchNewFrame();
  24178. this._activeIndices.fetchNewFrame();
  24179. this._activeBones.fetchNewFrame();
  24180. this._meshesForIntersections.reset();
  24181. this.resetCachedMaterial();
  24182. this.onBeforeAnimationsObservable.notifyObservers(this);
  24183. // Actions
  24184. if (this.actionManager) {
  24185. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24186. }
  24187. //Simplification Queue
  24188. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24189. this.simplificationQueue.executeNext();
  24190. }
  24191. if (this._engine.isDeterministicLockStep()) {
  24192. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24193. var defaultFPS = (60.0 / 1000.0);
  24194. var defaultFrameTime = 1000 / 60; // frame time in MS
  24195. if (this._physicsEngine) {
  24196. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24197. }
  24198. var stepsTaken = 0;
  24199. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24200. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24201. internalSteps = Math.min(internalSteps, maxSubSteps);
  24202. do {
  24203. this.onBeforeStepObservable.notifyObservers(this);
  24204. // Animations
  24205. this._animationRatio = defaultFrameTime * defaultFPS;
  24206. this._animate();
  24207. this.onAfterAnimationsObservable.notifyObservers(this);
  24208. // Physics
  24209. if (this._physicsEngine) {
  24210. this.onBeforePhysicsObservable.notifyObservers(this);
  24211. this._physicsEngine._step(defaultFrameTime / 1000);
  24212. this.onAfterPhysicsObservable.notifyObservers(this);
  24213. }
  24214. this.onAfterStepObservable.notifyObservers(this);
  24215. this._currentStepId++;
  24216. stepsTaken++;
  24217. deltaTime -= defaultFrameTime;
  24218. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24219. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24220. }
  24221. else {
  24222. // Animations
  24223. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24224. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24225. this._animate();
  24226. this.onAfterAnimationsObservable.notifyObservers(this);
  24227. // Physics
  24228. if (this._physicsEngine) {
  24229. this.onBeforePhysicsObservable.notifyObservers(this);
  24230. this._physicsEngine._step(deltaTime / 1000.0);
  24231. this.onAfterPhysicsObservable.notifyObservers(this);
  24232. }
  24233. }
  24234. // update gamepad manager
  24235. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24236. this._gamepadManager._checkGamepadsStatus();
  24237. }
  24238. // Before render
  24239. this.onBeforeRenderObservable.notifyObservers(this);
  24240. // Update Cameras
  24241. if (this.activeCameras.length > 0) {
  24242. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24243. var camera = this.activeCameras[cameraIndex];
  24244. camera.update();
  24245. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24246. // rig cameras
  24247. for (var index = 0; index < camera._rigCameras.length; index++) {
  24248. camera._rigCameras[index].update();
  24249. }
  24250. }
  24251. }
  24252. }
  24253. else if (this.activeCamera) {
  24254. this.activeCamera.update();
  24255. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24256. // rig cameras
  24257. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24258. this.activeCamera._rigCameras[index].update();
  24259. }
  24260. }
  24261. }
  24262. // Customs render targets
  24263. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24264. var engine = this.getEngine();
  24265. var currentActiveCamera = this.activeCamera;
  24266. if (this.renderTargetsEnabled) {
  24267. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24268. this._intermediateRendering = true;
  24269. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24270. var renderTarget = this.customRenderTargets[customIndex];
  24271. if (renderTarget._shouldRender()) {
  24272. this._renderId++;
  24273. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24274. if (!this.activeCamera)
  24275. throw new Error("Active camera not set");
  24276. // Viewport
  24277. engine.setViewport(this.activeCamera.viewport);
  24278. // Camera
  24279. this.updateTransformMatrix();
  24280. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24281. }
  24282. }
  24283. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24284. this._intermediateRendering = false;
  24285. this._renderId++;
  24286. }
  24287. // Restore back buffer
  24288. if (this.customRenderTargets.length > 0) {
  24289. engine.restoreDefaultFramebuffer();
  24290. }
  24291. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24292. this.activeCamera = currentActiveCamera;
  24293. // Procedural textures
  24294. if (this.proceduralTexturesEnabled) {
  24295. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24296. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24297. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24298. if (proceduralTexture._shouldRender()) {
  24299. proceduralTexture.render();
  24300. }
  24301. }
  24302. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24303. }
  24304. // Clear
  24305. if (this.autoClearDepthAndStencil || this.autoClear) {
  24306. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24307. }
  24308. // Shadows
  24309. if (this.shadowsEnabled) {
  24310. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24311. var light = this.lights[lightIndex];
  24312. var shadowGenerator = light.getShadowGenerator();
  24313. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24314. var shadowMap = (shadowGenerator.getShadowMap());
  24315. if (this.textures.indexOf(shadowMap) !== -1) {
  24316. this._renderTargets.push(shadowMap);
  24317. }
  24318. }
  24319. }
  24320. }
  24321. // Depth renderer
  24322. for (var key in this._depthRenderer) {
  24323. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24324. }
  24325. // Geometry renderer
  24326. if (this._geometryBufferRenderer) {
  24327. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24328. }
  24329. // RenderPipeline
  24330. if (this._postProcessRenderPipelineManager) {
  24331. this._postProcessRenderPipelineManager.update();
  24332. }
  24333. // Multi-cameras?
  24334. if (this.activeCameras.length > 0) {
  24335. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24336. if (cameraIndex > 0) {
  24337. this._engine.clear(null, false, true, true);
  24338. }
  24339. this._processSubCameras(this.activeCameras[cameraIndex]);
  24340. }
  24341. }
  24342. else {
  24343. if (!this.activeCamera) {
  24344. throw new Error("No camera defined");
  24345. }
  24346. this._processSubCameras(this.activeCamera);
  24347. }
  24348. // Intersection checks
  24349. this._checkIntersections();
  24350. // Update the audio listener attached to the camera
  24351. if (BABYLON.AudioEngine) {
  24352. this._updateAudioParameters();
  24353. }
  24354. // After render
  24355. if (this.afterRender) {
  24356. this.afterRender();
  24357. }
  24358. this.onAfterRenderObservable.notifyObservers(this);
  24359. // Cleaning
  24360. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24361. var data = this._toBeDisposed.data[index];
  24362. if (data) {
  24363. data.dispose();
  24364. }
  24365. this._toBeDisposed[index] = null;
  24366. }
  24367. this._toBeDisposed.reset();
  24368. if (this.dumpNextRenderTargets) {
  24369. this.dumpNextRenderTargets = false;
  24370. }
  24371. this._activeBones.addCount(0, true);
  24372. this._activeIndices.addCount(0, true);
  24373. this._activeParticles.addCount(0, true);
  24374. };
  24375. Scene.prototype._updateAudioParameters = function () {
  24376. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24377. return;
  24378. }
  24379. var listeningCamera;
  24380. var audioEngine = BABYLON.Engine.audioEngine;
  24381. if (this.activeCameras.length > 0) {
  24382. listeningCamera = this.activeCameras[0];
  24383. }
  24384. else {
  24385. listeningCamera = this.activeCamera;
  24386. }
  24387. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24388. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24389. // for VR cameras
  24390. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24391. listeningCamera = listeningCamera.rigCameras[0];
  24392. }
  24393. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24394. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24395. cameraDirection.normalize();
  24396. // To avoid some errors on GearVR
  24397. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24398. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24399. }
  24400. var i;
  24401. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24402. var sound = this.mainSoundTrack.soundCollection[i];
  24403. if (sound.useCustomAttenuation) {
  24404. sound.updateDistanceFromListener();
  24405. }
  24406. }
  24407. for (i = 0; i < this.soundTracks.length; i++) {
  24408. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24409. sound = this.soundTracks[i].soundCollection[j];
  24410. if (sound.useCustomAttenuation) {
  24411. sound.updateDistanceFromListener();
  24412. }
  24413. }
  24414. }
  24415. }
  24416. };
  24417. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24418. // Audio
  24419. get: function () {
  24420. return this._audioEnabled;
  24421. },
  24422. set: function (value) {
  24423. this._audioEnabled = value;
  24424. if (BABYLON.AudioEngine) {
  24425. if (this._audioEnabled) {
  24426. this._enableAudio();
  24427. }
  24428. else {
  24429. this._disableAudio();
  24430. }
  24431. }
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Scene.prototype._disableAudio = function () {
  24437. var i;
  24438. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24439. this.mainSoundTrack.soundCollection[i].pause();
  24440. }
  24441. for (i = 0; i < this.soundTracks.length; i++) {
  24442. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24443. this.soundTracks[i].soundCollection[j].pause();
  24444. }
  24445. }
  24446. };
  24447. Scene.prototype._enableAudio = function () {
  24448. var i;
  24449. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24450. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24451. this.mainSoundTrack.soundCollection[i].play();
  24452. }
  24453. }
  24454. for (i = 0; i < this.soundTracks.length; i++) {
  24455. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24456. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24457. this.soundTracks[i].soundCollection[j].play();
  24458. }
  24459. }
  24460. }
  24461. };
  24462. Object.defineProperty(Scene.prototype, "headphone", {
  24463. get: function () {
  24464. return this._headphone;
  24465. },
  24466. set: function (value) {
  24467. this._headphone = value;
  24468. if (BABYLON.AudioEngine) {
  24469. if (this._headphone) {
  24470. this._switchAudioModeForHeadphones();
  24471. }
  24472. else {
  24473. this._switchAudioModeForNormalSpeakers();
  24474. }
  24475. }
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Scene.prototype._switchAudioModeForHeadphones = function () {
  24481. this.mainSoundTrack.switchPanningModelToHRTF();
  24482. for (var i = 0; i < this.soundTracks.length; i++) {
  24483. this.soundTracks[i].switchPanningModelToHRTF();
  24484. }
  24485. };
  24486. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24487. this.mainSoundTrack.switchPanningModelToEqualPower();
  24488. for (var i = 0; i < this.soundTracks.length; i++) {
  24489. this.soundTracks[i].switchPanningModelToEqualPower();
  24490. }
  24491. };
  24492. /**
  24493. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24494. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24495. * @returns the created depth renderer
  24496. */
  24497. Scene.prototype.enableDepthRenderer = function (camera) {
  24498. camera = camera || this.activeCamera;
  24499. if (!camera) {
  24500. throw "No camera available to enable depth renderer";
  24501. }
  24502. if (!this._depthRenderer[camera.id]) {
  24503. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24504. }
  24505. return this._depthRenderer[camera.id];
  24506. };
  24507. /**
  24508. * Disables a depth renderer for a given camera
  24509. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24510. */
  24511. Scene.prototype.disableDepthRenderer = function (camera) {
  24512. camera = camera || this.activeCamera;
  24513. if (!camera || !this._depthRenderer[camera.id]) {
  24514. return;
  24515. }
  24516. this._depthRenderer[camera.id].dispose();
  24517. delete this._depthRenderer[camera.id];
  24518. };
  24519. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24520. if (ratio === void 0) { ratio = 1; }
  24521. if (this._geometryBufferRenderer) {
  24522. return this._geometryBufferRenderer;
  24523. }
  24524. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24525. if (!this._geometryBufferRenderer.isSupported) {
  24526. this._geometryBufferRenderer = null;
  24527. }
  24528. return this._geometryBufferRenderer;
  24529. };
  24530. Scene.prototype.disableGeometryBufferRenderer = function () {
  24531. if (!this._geometryBufferRenderer) {
  24532. return;
  24533. }
  24534. this._geometryBufferRenderer.dispose();
  24535. this._geometryBufferRenderer = null;
  24536. };
  24537. Scene.prototype.freezeMaterials = function () {
  24538. for (var i = 0; i < this.materials.length; i++) {
  24539. this.materials[i].freeze();
  24540. }
  24541. };
  24542. Scene.prototype.unfreezeMaterials = function () {
  24543. for (var i = 0; i < this.materials.length; i++) {
  24544. this.materials[i].unfreeze();
  24545. }
  24546. };
  24547. Scene.prototype.dispose = function () {
  24548. this.beforeRender = null;
  24549. this.afterRender = null;
  24550. this.skeletons = [];
  24551. this.morphTargetManagers = [];
  24552. this.importedMeshesFiles = new Array();
  24553. this.stopAllAnimations();
  24554. this.resetCachedMaterial();
  24555. for (var key in this._depthRenderer) {
  24556. this._depthRenderer[key].dispose();
  24557. }
  24558. if (this._gamepadManager) {
  24559. this._gamepadManager.dispose();
  24560. this._gamepadManager = null;
  24561. }
  24562. // Smart arrays
  24563. if (this.activeCamera) {
  24564. this.activeCamera._activeMeshes.dispose();
  24565. this.activeCamera = null;
  24566. }
  24567. this._activeMeshes.dispose();
  24568. this._renderingManager.dispose();
  24569. this._processedMaterials.dispose();
  24570. this._activeParticleSystems.dispose();
  24571. this._activeSkeletons.dispose();
  24572. this._softwareSkinnedMeshes.dispose();
  24573. this._renderTargets.dispose();
  24574. if (this._boundingBoxRenderer) {
  24575. this._boundingBoxRenderer.dispose();
  24576. }
  24577. this._meshesForIntersections.dispose();
  24578. this._toBeDisposed.dispose();
  24579. // Abort active requests
  24580. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24581. var request = _a[_i];
  24582. request.abort();
  24583. }
  24584. // Debug layer
  24585. if (this._debugLayer) {
  24586. this._debugLayer.hide();
  24587. }
  24588. // Events
  24589. this.onDisposeObservable.notifyObservers(this);
  24590. this.onDisposeObservable.clear();
  24591. this.onBeforeRenderObservable.clear();
  24592. this.onAfterRenderObservable.clear();
  24593. this.OnBeforeRenderTargetsRenderObservable.clear();
  24594. this.OnAfterRenderTargetsRenderObservable.clear();
  24595. this.onAfterStepObservable.clear();
  24596. this.onBeforeStepObservable.clear();
  24597. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24598. this.onAfterActiveMeshesEvaluationObservable.clear();
  24599. this.onBeforeParticlesRenderingObservable.clear();
  24600. this.onAfterParticlesRenderingObservable.clear();
  24601. this.onBeforeSpritesRenderingObservable.clear();
  24602. this.onAfterSpritesRenderingObservable.clear();
  24603. this.onBeforeDrawPhaseObservable.clear();
  24604. this.onAfterDrawPhaseObservable.clear();
  24605. this.onBeforePhysicsObservable.clear();
  24606. this.onAfterPhysicsObservable.clear();
  24607. this.onBeforeAnimationsObservable.clear();
  24608. this.onAfterAnimationsObservable.clear();
  24609. this.onDataLoadedObservable.clear();
  24610. this.detachControl();
  24611. // Release sounds & sounds tracks
  24612. if (BABYLON.AudioEngine) {
  24613. this.disposeSounds();
  24614. }
  24615. // VR Helper
  24616. if (this.VRHelper) {
  24617. this.VRHelper.dispose();
  24618. }
  24619. // Detach cameras
  24620. var canvas = this._engine.getRenderingCanvas();
  24621. if (canvas) {
  24622. var index;
  24623. for (index = 0; index < this.cameras.length; index++) {
  24624. this.cameras[index].detachControl(canvas);
  24625. }
  24626. }
  24627. // Release animation groups
  24628. while (this.animationGroups.length) {
  24629. this.animationGroups[0].dispose();
  24630. }
  24631. // Release lights
  24632. while (this.lights.length) {
  24633. this.lights[0].dispose();
  24634. }
  24635. // Release meshes
  24636. while (this.meshes.length) {
  24637. this.meshes[0].dispose(true);
  24638. }
  24639. while (this.transformNodes.length) {
  24640. this.removeTransformNode(this.transformNodes[0]);
  24641. }
  24642. // Release cameras
  24643. while (this.cameras.length) {
  24644. this.cameras[0].dispose();
  24645. }
  24646. // Release materials
  24647. if (this.defaultMaterial) {
  24648. this.defaultMaterial.dispose();
  24649. }
  24650. while (this.multiMaterials.length) {
  24651. this.multiMaterials[0].dispose();
  24652. }
  24653. while (this.materials.length) {
  24654. this.materials[0].dispose();
  24655. }
  24656. // Release particles
  24657. while (this.particleSystems.length) {
  24658. this.particleSystems[0].dispose();
  24659. }
  24660. // Release sprites
  24661. while (this.spriteManagers.length) {
  24662. this.spriteManagers[0].dispose();
  24663. }
  24664. // Release postProcesses
  24665. while (this.postProcesses.length) {
  24666. this.postProcesses[0].dispose();
  24667. }
  24668. // Release layers
  24669. while (this.layers.length) {
  24670. this.layers[0].dispose();
  24671. }
  24672. while (this.effectLayers.length) {
  24673. this.effectLayers[0].dispose();
  24674. }
  24675. // Release textures
  24676. while (this.textures.length) {
  24677. this.textures[0].dispose();
  24678. }
  24679. // Release UBO
  24680. this._sceneUbo.dispose();
  24681. if (this._alternateSceneUbo) {
  24682. this._alternateSceneUbo.dispose();
  24683. }
  24684. // Post-processes
  24685. this.postProcessManager.dispose();
  24686. if (this._postProcessRenderPipelineManager) {
  24687. this._postProcessRenderPipelineManager.dispose();
  24688. }
  24689. // Physics
  24690. if (this._physicsEngine) {
  24691. this.disablePhysicsEngine();
  24692. }
  24693. // Remove from engine
  24694. index = this._engine.scenes.indexOf(this);
  24695. if (index > -1) {
  24696. this._engine.scenes.splice(index, 1);
  24697. }
  24698. this._engine.wipeCaches(true);
  24699. this._isDisposed = true;
  24700. };
  24701. Object.defineProperty(Scene.prototype, "isDisposed", {
  24702. get: function () {
  24703. return this._isDisposed;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. // Release sounds & sounds tracks
  24709. Scene.prototype.disposeSounds = function () {
  24710. if (!this._mainSoundTrack) {
  24711. return;
  24712. }
  24713. this.mainSoundTrack.dispose();
  24714. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24715. this.soundTracks[scIndex].dispose();
  24716. }
  24717. };
  24718. // Octrees
  24719. /**
  24720. * Get the world extend vectors with an optional filter
  24721. *
  24722. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24723. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24724. */
  24725. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24726. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24727. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24728. filterPredicate = filterPredicate || (function () { return true; });
  24729. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24730. mesh.computeWorldMatrix(true);
  24731. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24732. return;
  24733. }
  24734. var boundingInfo = mesh.getBoundingInfo();
  24735. var minBox = boundingInfo.boundingBox.minimumWorld;
  24736. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24737. BABYLON.Tools.CheckExtends(minBox, min, max);
  24738. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24739. });
  24740. return {
  24741. min: min,
  24742. max: max
  24743. };
  24744. };
  24745. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24746. if (maxCapacity === void 0) { maxCapacity = 64; }
  24747. if (maxDepth === void 0) { maxDepth = 2; }
  24748. if (!this._selectionOctree) {
  24749. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24750. }
  24751. var worldExtends = this.getWorldExtends();
  24752. // Update octree
  24753. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24754. return this._selectionOctree;
  24755. };
  24756. // Picking
  24757. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24758. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24759. var result = BABYLON.Ray.Zero();
  24760. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24761. return result;
  24762. };
  24763. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24764. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24765. var engine = this._engine;
  24766. if (!camera) {
  24767. if (!this.activeCamera)
  24768. throw new Error("Active camera not set");
  24769. camera = this.activeCamera;
  24770. }
  24771. var cameraViewport = camera.viewport;
  24772. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24773. // Moving coordinates to local viewport world
  24774. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24775. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24776. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24777. return this;
  24778. };
  24779. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24780. var result = BABYLON.Ray.Zero();
  24781. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24782. return result;
  24783. };
  24784. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24785. if (!BABYLON.PickingInfo) {
  24786. return this;
  24787. }
  24788. var engine = this._engine;
  24789. if (!camera) {
  24790. if (!this.activeCamera)
  24791. throw new Error("Active camera not set");
  24792. camera = this.activeCamera;
  24793. }
  24794. var cameraViewport = camera.viewport;
  24795. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24796. var identity = BABYLON.Matrix.Identity();
  24797. // Moving coordinates to local viewport world
  24798. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24799. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24800. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24801. return this;
  24802. };
  24803. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24804. if (!BABYLON.PickingInfo) {
  24805. return null;
  24806. }
  24807. var pickingInfo = null;
  24808. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24809. var mesh = this.meshes[meshIndex];
  24810. if (predicate) {
  24811. if (!predicate(mesh)) {
  24812. continue;
  24813. }
  24814. }
  24815. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24816. continue;
  24817. }
  24818. var world = mesh.getWorldMatrix();
  24819. var ray = rayFunction(world);
  24820. var result = mesh.intersects(ray, fastCheck);
  24821. if (!result || !result.hit)
  24822. continue;
  24823. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24824. continue;
  24825. pickingInfo = result;
  24826. if (fastCheck) {
  24827. break;
  24828. }
  24829. }
  24830. return pickingInfo || new BABYLON.PickingInfo();
  24831. };
  24832. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24833. if (!BABYLON.PickingInfo) {
  24834. return null;
  24835. }
  24836. var pickingInfos = new Array();
  24837. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24838. var mesh = this.meshes[meshIndex];
  24839. if (predicate) {
  24840. if (!predicate(mesh)) {
  24841. continue;
  24842. }
  24843. }
  24844. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24845. continue;
  24846. }
  24847. var world = mesh.getWorldMatrix();
  24848. var ray = rayFunction(world);
  24849. var result = mesh.intersects(ray, false);
  24850. if (!result || !result.hit)
  24851. continue;
  24852. pickingInfos.push(result);
  24853. }
  24854. return pickingInfos;
  24855. };
  24856. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24857. if (!BABYLON.PickingInfo) {
  24858. return null;
  24859. }
  24860. var pickingInfo = null;
  24861. if (!camera) {
  24862. if (!this.activeCamera) {
  24863. return null;
  24864. }
  24865. camera = this.activeCamera;
  24866. }
  24867. if (this.spriteManagers.length > 0) {
  24868. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24869. var spriteManager = this.spriteManagers[spriteIndex];
  24870. if (!spriteManager.isPickable) {
  24871. continue;
  24872. }
  24873. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24874. if (!result || !result.hit)
  24875. continue;
  24876. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24877. continue;
  24878. pickingInfo = result;
  24879. if (fastCheck) {
  24880. break;
  24881. }
  24882. }
  24883. }
  24884. return pickingInfo || new BABYLON.PickingInfo();
  24885. };
  24886. /** Launch a ray to try to pick a mesh in the scene
  24887. * @param x position on screen
  24888. * @param y position on screen
  24889. * @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
  24890. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24891. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24892. */
  24893. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24894. var _this = this;
  24895. if (!BABYLON.PickingInfo) {
  24896. return null;
  24897. }
  24898. return this._internalPick(function (world) {
  24899. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24900. return _this._tempPickingRay;
  24901. }, predicate, fastCheck);
  24902. };
  24903. /** Launch a ray to try to pick a sprite in the scene
  24904. * @param x position on screen
  24905. * @param y position on screen
  24906. * @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
  24907. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24908. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24909. */
  24910. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24911. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24912. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24913. };
  24914. /** Use the given ray to pick a mesh in the scene
  24915. * @param ray The ray to use to pick meshes
  24916. * @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
  24917. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24918. */
  24919. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24920. var _this = this;
  24921. return this._internalPick(function (world) {
  24922. if (!_this._pickWithRayInverseMatrix) {
  24923. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24924. }
  24925. world.invertToRef(_this._pickWithRayInverseMatrix);
  24926. if (!_this._cachedRayForTransform) {
  24927. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24928. }
  24929. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24930. return _this._cachedRayForTransform;
  24931. }, predicate, fastCheck);
  24932. };
  24933. /**
  24934. * Launch a ray to try to pick a mesh in the scene
  24935. * @param x X position on screen
  24936. * @param y Y position on screen
  24937. * @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
  24938. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24939. */
  24940. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24941. var _this = this;
  24942. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24943. };
  24944. /**
  24945. * Launch a ray to try to pick a mesh in the scene
  24946. * @param ray Ray to use
  24947. * @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
  24948. */
  24949. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24950. var _this = this;
  24951. return this._internalMultiPick(function (world) {
  24952. if (!_this._pickWithRayInverseMatrix) {
  24953. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24954. }
  24955. world.invertToRef(_this._pickWithRayInverseMatrix);
  24956. if (!_this._cachedRayForTransform) {
  24957. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24958. }
  24959. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24960. return _this._cachedRayForTransform;
  24961. }, predicate);
  24962. };
  24963. Scene.prototype.setPointerOverMesh = function (mesh) {
  24964. if (this._pointerOverMesh === mesh) {
  24965. return;
  24966. }
  24967. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24968. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24969. }
  24970. this._pointerOverMesh = mesh;
  24971. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24972. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24973. }
  24974. };
  24975. Scene.prototype.getPointerOverMesh = function () {
  24976. return this._pointerOverMesh;
  24977. };
  24978. Scene.prototype.setPointerOverSprite = function (sprite) {
  24979. if (this._pointerOverSprite === sprite) {
  24980. return;
  24981. }
  24982. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24983. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24984. }
  24985. this._pointerOverSprite = sprite;
  24986. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24987. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24988. }
  24989. };
  24990. Scene.prototype.getPointerOverSprite = function () {
  24991. return this._pointerOverSprite;
  24992. };
  24993. // Physics
  24994. Scene.prototype.getPhysicsEngine = function () {
  24995. return this._physicsEngine;
  24996. };
  24997. /**
  24998. * Enables physics to the current scene
  24999. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25000. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25001. * @return {boolean} was the physics engine initialized
  25002. */
  25003. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25004. if (gravity === void 0) { gravity = null; }
  25005. if (this._physicsEngine) {
  25006. return true;
  25007. }
  25008. try {
  25009. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25010. return true;
  25011. }
  25012. catch (e) {
  25013. BABYLON.Tools.Error(e.message);
  25014. return false;
  25015. }
  25016. };
  25017. Scene.prototype.disablePhysicsEngine = function () {
  25018. if (!this._physicsEngine) {
  25019. return;
  25020. }
  25021. this._physicsEngine.dispose();
  25022. this._physicsEngine = null;
  25023. };
  25024. Scene.prototype.isPhysicsEnabled = function () {
  25025. return this._physicsEngine !== undefined;
  25026. };
  25027. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25028. var mesh = compound.parts[0].mesh;
  25029. if (mesh.physicsImpostor) {
  25030. mesh.physicsImpostor.dispose();
  25031. mesh.physicsImpostor = null;
  25032. }
  25033. };
  25034. // Misc.
  25035. Scene.prototype._rebuildGeometries = function () {
  25036. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25037. var geometry = _a[_i];
  25038. geometry._rebuild();
  25039. }
  25040. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25041. var mesh = _c[_b];
  25042. mesh._rebuild();
  25043. }
  25044. if (this.postProcessManager) {
  25045. this.postProcessManager._rebuild();
  25046. }
  25047. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25048. var layer = _e[_d];
  25049. layer._rebuild();
  25050. }
  25051. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25052. var effectLayer = _g[_f];
  25053. effectLayer._rebuild();
  25054. }
  25055. if (this._boundingBoxRenderer) {
  25056. this._boundingBoxRenderer._rebuild();
  25057. }
  25058. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25059. var system = _j[_h];
  25060. system.rebuild();
  25061. }
  25062. if (this._postProcessRenderPipelineManager) {
  25063. this._postProcessRenderPipelineManager._rebuild();
  25064. }
  25065. };
  25066. Scene.prototype._rebuildTextures = function () {
  25067. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25068. var texture = _a[_i];
  25069. texture._rebuild();
  25070. }
  25071. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25072. };
  25073. /**
  25074. * Creates a default light for the scene.
  25075. * @param replace Whether to replace the existing lights in the scene.
  25076. */
  25077. Scene.prototype.createDefaultLight = function (replace) {
  25078. if (replace === void 0) { replace = false; }
  25079. // Dispose existing light in replace mode.
  25080. if (replace) {
  25081. if (this.lights) {
  25082. for (var i = 0; i < this.lights.length; i++) {
  25083. this.lights[i].dispose();
  25084. }
  25085. }
  25086. }
  25087. // Light
  25088. if (this.lights.length === 0) {
  25089. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25090. }
  25091. };
  25092. /**
  25093. * Creates a default camera for the scene.
  25094. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25095. * @param replace Whether to replace the existing active camera in the scene.
  25096. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25097. */
  25098. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25099. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25100. if (replace === void 0) { replace = false; }
  25101. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25102. // Dispose existing camera in replace mode.
  25103. if (replace) {
  25104. if (this.activeCamera) {
  25105. this.activeCamera.dispose();
  25106. this.activeCamera = null;
  25107. }
  25108. }
  25109. // Camera
  25110. if (!this.activeCamera) {
  25111. var worldExtends = this.getWorldExtends();
  25112. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25113. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25114. var camera;
  25115. var radius = worldSize.length() * 1.5;
  25116. // empty scene scenario!
  25117. if (!isFinite(radius)) {
  25118. radius = 1;
  25119. worldCenter.copyFromFloats(0, 0, 0);
  25120. }
  25121. if (createArcRotateCamera) {
  25122. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25123. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25124. arcRotateCamera.wheelPrecision = 100 / radius;
  25125. camera = arcRotateCamera;
  25126. }
  25127. else {
  25128. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25129. freeCamera.setTarget(worldCenter);
  25130. camera = freeCamera;
  25131. }
  25132. camera.minZ = radius * 0.01;
  25133. camera.maxZ = radius * 1000;
  25134. camera.speed = radius * 0.2;
  25135. this.activeCamera = camera;
  25136. var canvas = this.getEngine().getRenderingCanvas();
  25137. if (attachCameraControls && canvas) {
  25138. camera.attachControl(canvas);
  25139. }
  25140. }
  25141. };
  25142. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25143. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25144. if (replace === void 0) { replace = false; }
  25145. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25146. this.createDefaultLight(replace);
  25147. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25148. };
  25149. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25150. if (pbr === void 0) { pbr = false; }
  25151. if (scale === void 0) { scale = 1000; }
  25152. if (blur === void 0) { blur = 0; }
  25153. if (environmentTexture) {
  25154. this.environmentTexture = environmentTexture;
  25155. }
  25156. if (!this.environmentTexture) {
  25157. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25158. return null;
  25159. }
  25160. // Skybox
  25161. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25162. if (pbr) {
  25163. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25164. hdrSkyboxMaterial.backFaceCulling = false;
  25165. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25166. if (hdrSkyboxMaterial.reflectionTexture) {
  25167. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25168. }
  25169. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25170. hdrSkyboxMaterial.disableLighting = true;
  25171. hdrSkyboxMaterial.twoSidedLighting = true;
  25172. hdrSkybox.infiniteDistance = true;
  25173. hdrSkybox.material = hdrSkyboxMaterial;
  25174. }
  25175. else {
  25176. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25177. skyboxMaterial.backFaceCulling = false;
  25178. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25179. if (skyboxMaterial.reflectionTexture) {
  25180. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25181. }
  25182. skyboxMaterial.disableLighting = true;
  25183. hdrSkybox.infiniteDistance = true;
  25184. hdrSkybox.material = skyboxMaterial;
  25185. }
  25186. return hdrSkybox;
  25187. };
  25188. Scene.prototype.createDefaultEnvironment = function (options) {
  25189. if (BABYLON.EnvironmentHelper) {
  25190. return new BABYLON.EnvironmentHelper(options, this);
  25191. }
  25192. return null;
  25193. };
  25194. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25195. if (webVROptions === void 0) { webVROptions = {}; }
  25196. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25197. };
  25198. // Tags
  25199. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25200. if (tagsQuery === undefined) {
  25201. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25202. return list;
  25203. }
  25204. var listByTags = [];
  25205. forEach = forEach || (function (item) { return; });
  25206. for (var i in list) {
  25207. var item = list[i];
  25208. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25209. listByTags.push(item);
  25210. forEach(item);
  25211. }
  25212. }
  25213. return listByTags;
  25214. };
  25215. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25216. return this._getByTags(this.meshes, tagsQuery, forEach);
  25217. };
  25218. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25219. return this._getByTags(this.cameras, tagsQuery, forEach);
  25220. };
  25221. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25222. return this._getByTags(this.lights, tagsQuery, forEach);
  25223. };
  25224. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25225. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25226. };
  25227. /**
  25228. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25229. * This allowed control for front to back rendering or reversly depending of the special needs.
  25230. *
  25231. * @param renderingGroupId The rendering group id corresponding to its index
  25232. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25233. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25234. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25235. */
  25236. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25237. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25238. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25239. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25240. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25241. };
  25242. /**
  25243. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25244. *
  25245. * @param renderingGroupId The rendering group id corresponding to its index
  25246. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25247. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25248. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25249. */
  25250. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25251. if (depth === void 0) { depth = true; }
  25252. if (stencil === void 0) { stencil = true; }
  25253. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25254. };
  25255. /**
  25256. * Will flag all materials as dirty to trigger new shader compilation
  25257. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25258. */
  25259. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25260. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25261. var material = _a[_i];
  25262. if (predicate && !predicate(material)) {
  25263. continue;
  25264. }
  25265. material.markAsDirty(flag);
  25266. }
  25267. };
  25268. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25269. var _this = this;
  25270. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25271. this._activeRequests.push(request);
  25272. request.onCompleteObservable.add(function (request) {
  25273. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25274. });
  25275. return request;
  25276. };
  25277. /** @ignore */
  25278. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25279. var _this = this;
  25280. return new Promise(function (resolve, reject) {
  25281. _this._loadFile(url, function (data) {
  25282. resolve(data);
  25283. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25284. reject(exception);
  25285. });
  25286. });
  25287. };
  25288. // Statics
  25289. Scene._FOGMODE_NONE = 0;
  25290. Scene._FOGMODE_EXP = 1;
  25291. Scene._FOGMODE_EXP2 = 2;
  25292. Scene._FOGMODE_LINEAR = 3;
  25293. Scene._uniqueIdCounter = 0;
  25294. Scene.MinDeltaTime = 1.0;
  25295. Scene.MaxDeltaTime = 1000.0;
  25296. /** The distance in pixel that you have to move to prevent some events */
  25297. Scene.DragMovementThreshold = 10; // in pixels
  25298. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25299. Scene.LongPressDelay = 500; // in milliseconds
  25300. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25301. Scene.DoubleClickDelay = 300; // in milliseconds
  25302. /** If you need to check double click without raising a single click at first click, enable this flag */
  25303. Scene.ExclusiveDoubleClickMode = false;
  25304. return Scene;
  25305. }());
  25306. BABYLON.Scene = Scene;
  25307. })(BABYLON || (BABYLON = {}));
  25308. //# sourceMappingURL=babylon.scene.js.map
  25309. var BABYLON;
  25310. (function (BABYLON) {
  25311. /**
  25312. * Set of assets to keep when moving a scene into an asset container.
  25313. */
  25314. var KeepAssets = /** @class */ (function () {
  25315. function KeepAssets() {
  25316. /**
  25317. * Cameras to keep.
  25318. */
  25319. this.cameras = new Array();
  25320. /**
  25321. * Lights to keep.
  25322. */
  25323. this.lights = new Array();
  25324. /**
  25325. * Meshes to keep.
  25326. */
  25327. this.meshes = new Array();
  25328. /**
  25329. * Skeletons to keep.
  25330. */
  25331. this.skeletons = new Array();
  25332. /**
  25333. * ParticleSystems to keep.
  25334. */
  25335. this.particleSystems = new Array();
  25336. /**
  25337. * Animations to keep.
  25338. */
  25339. this.animations = new Array();
  25340. /**
  25341. * MultiMaterials to keep.
  25342. */
  25343. this.multiMaterials = new Array();
  25344. /**
  25345. * Materials to keep.
  25346. */
  25347. this.materials = new Array();
  25348. /**
  25349. * MorphTargetManagers to keep.
  25350. */
  25351. this.morphTargetManagers = new Array();
  25352. /**
  25353. * Geometries to keep.
  25354. */
  25355. this.geometries = new Array();
  25356. /**
  25357. * TransformNodes to keep.
  25358. */
  25359. this.transformNodes = new Array();
  25360. /**
  25361. * LensFlareSystems to keep.
  25362. */
  25363. this.lensFlareSystems = new Array();
  25364. /**
  25365. * ShadowGenerators to keep.
  25366. */
  25367. this.shadowGenerators = new Array();
  25368. /**
  25369. * ActionManagers to keep.
  25370. */
  25371. this.actionManagers = new Array();
  25372. /**
  25373. * Sounds to keep.
  25374. */
  25375. this.sounds = new Array();
  25376. }
  25377. return KeepAssets;
  25378. }());
  25379. BABYLON.KeepAssets = KeepAssets;
  25380. /**
  25381. * Container with a set of assets that can be added or removed from a scene.
  25382. */
  25383. var AssetContainer = /** @class */ (function () {
  25384. /**
  25385. * Instantiates an AssetContainer.
  25386. * @param scene The scene the AssetContainer belongs to.
  25387. */
  25388. function AssetContainer(scene) {
  25389. // Objects
  25390. /**
  25391. * Cameras populated in the container.
  25392. */
  25393. this.cameras = new Array();
  25394. /**
  25395. * Lights populated in the container.
  25396. */
  25397. this.lights = new Array();
  25398. /**
  25399. * Meshes populated in the container.
  25400. */
  25401. this.meshes = new Array();
  25402. /**
  25403. * Skeletons populated in the container.
  25404. */
  25405. this.skeletons = new Array();
  25406. /**
  25407. * ParticleSystems populated in the container.
  25408. */
  25409. this.particleSystems = new Array();
  25410. /**
  25411. * Animations populated in the container.
  25412. */
  25413. this.animations = new Array();
  25414. /**
  25415. * MultiMaterials populated in the container.
  25416. */
  25417. this.multiMaterials = new Array();
  25418. /**
  25419. * Materials populated in the container.
  25420. */
  25421. this.materials = new Array();
  25422. /**
  25423. * MorphTargetManagers populated in the container.
  25424. */
  25425. this.morphTargetManagers = new Array();
  25426. /**
  25427. * Geometries populated in the container.
  25428. */
  25429. this.geometries = new Array();
  25430. /**
  25431. * TransformNodes populated in the container.
  25432. */
  25433. this.transformNodes = new Array();
  25434. /**
  25435. * LensFlareSystems populated in the container.
  25436. */
  25437. this.lensFlareSystems = new Array();
  25438. /**
  25439. * ShadowGenerators populated in the container.
  25440. */
  25441. this.shadowGenerators = new Array();
  25442. /**
  25443. * ActionManagers populated in the container.
  25444. */
  25445. this.actionManagers = new Array();
  25446. /**
  25447. * Sounds populated in the container.
  25448. */
  25449. this.sounds = new Array();
  25450. this.scene = scene;
  25451. }
  25452. /**
  25453. * Adds all the assets from the container to the scene.
  25454. */
  25455. AssetContainer.prototype.addAllToScene = function () {
  25456. var _this = this;
  25457. this.cameras.forEach(function (o) {
  25458. _this.scene.addCamera(o);
  25459. });
  25460. this.lights.forEach(function (o) {
  25461. _this.scene.addLight(o);
  25462. });
  25463. this.meshes.forEach(function (o) {
  25464. _this.scene.addMesh(o);
  25465. });
  25466. this.skeletons.forEach(function (o) {
  25467. _this.scene.addSkeleton(o);
  25468. });
  25469. this.particleSystems.forEach(function (o) {
  25470. _this.scene.addParticleSystem(o);
  25471. });
  25472. this.animations.forEach(function (o) {
  25473. _this.scene.addAnimation(o);
  25474. });
  25475. this.multiMaterials.forEach(function (o) {
  25476. _this.scene.addMultiMaterial(o);
  25477. });
  25478. this.materials.forEach(function (o) {
  25479. _this.scene.addMaterial(o);
  25480. });
  25481. this.morphTargetManagers.forEach(function (o) {
  25482. _this.scene.addMorphTargetManager(o);
  25483. });
  25484. this.geometries.forEach(function (o) {
  25485. _this.scene.addGeometry(o);
  25486. });
  25487. this.transformNodes.forEach(function (o) {
  25488. _this.scene.addTransformNode(o);
  25489. });
  25490. this.lensFlareSystems.forEach(function (o) {
  25491. _this.scene.addLensFlareSystem(o);
  25492. });
  25493. this.actionManagers.forEach(function (o) {
  25494. _this.scene.addActionManager(o);
  25495. });
  25496. this.sounds.forEach(function (o) {
  25497. o.play();
  25498. o.autoplay = true;
  25499. _this.scene.mainSoundTrack.AddSound(o);
  25500. });
  25501. };
  25502. /**
  25503. * Removes all the assets in the container from the scene
  25504. */
  25505. AssetContainer.prototype.removeAllFromScene = function () {
  25506. var _this = this;
  25507. this.cameras.forEach(function (o) {
  25508. _this.scene.removeCamera(o);
  25509. });
  25510. this.lights.forEach(function (o) {
  25511. _this.scene.removeLight(o);
  25512. });
  25513. this.meshes.forEach(function (o) {
  25514. _this.scene.removeMesh(o);
  25515. });
  25516. this.skeletons.forEach(function (o) {
  25517. _this.scene.removeSkeleton(o);
  25518. });
  25519. this.particleSystems.forEach(function (o) {
  25520. _this.scene.removeParticleSystem(o);
  25521. });
  25522. this.animations.forEach(function (o) {
  25523. _this.scene.removeAnimation(o);
  25524. });
  25525. this.multiMaterials.forEach(function (o) {
  25526. _this.scene.removeMultiMaterial(o);
  25527. });
  25528. this.materials.forEach(function (o) {
  25529. _this.scene.removeMaterial(o);
  25530. });
  25531. this.morphTargetManagers.forEach(function (o) {
  25532. _this.scene.removeMorphTargetManager(o);
  25533. });
  25534. this.geometries.forEach(function (o) {
  25535. _this.scene.removeGeometry(o);
  25536. });
  25537. this.transformNodes.forEach(function (o) {
  25538. _this.scene.removeTransformNode(o);
  25539. });
  25540. this.lensFlareSystems.forEach(function (o) {
  25541. _this.scene.removeLensFlareSystem(o);
  25542. });
  25543. this.actionManagers.forEach(function (o) {
  25544. _this.scene.removeActionManager(o);
  25545. });
  25546. this.sounds.forEach(function (o) {
  25547. o.stop();
  25548. o.autoplay = false;
  25549. _this.scene.mainSoundTrack.RemoveSound(o);
  25550. });
  25551. };
  25552. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25553. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25554. var asset = sourceAssets_1[_i];
  25555. var move = true;
  25556. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25557. var keepAsset = keepAssets_1[_a];
  25558. if (asset === keepAsset) {
  25559. move = false;
  25560. break;
  25561. }
  25562. }
  25563. if (move) {
  25564. targetAssets.push(asset);
  25565. }
  25566. }
  25567. };
  25568. /**
  25569. * Removes all the assets contained in the scene and adds them to the container.
  25570. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25571. */
  25572. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25573. if (keepAssets === undefined) {
  25574. keepAssets = new KeepAssets();
  25575. }
  25576. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25577. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25578. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25579. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25580. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25581. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25582. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25583. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25584. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25585. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25586. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25587. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25588. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25589. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25590. this.removeAllFromScene();
  25591. };
  25592. return AssetContainer;
  25593. }());
  25594. BABYLON.AssetContainer = AssetContainer;
  25595. })(BABYLON || (BABYLON = {}));
  25596. //# sourceMappingURL=babylon.assetContainer.js.map
  25597. var BABYLON;
  25598. (function (BABYLON) {
  25599. var Buffer = /** @class */ (function () {
  25600. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25601. if (instanced === void 0) { instanced = false; }
  25602. if (engine instanceof BABYLON.Mesh) {
  25603. this._engine = engine.getScene().getEngine();
  25604. }
  25605. else {
  25606. this._engine = engine;
  25607. }
  25608. this._updatable = updatable;
  25609. this._instanced = instanced;
  25610. this._data = data;
  25611. this._strideSize = stride;
  25612. if (!postponeInternalCreation) {
  25613. this.create();
  25614. }
  25615. }
  25616. /**
  25617. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25618. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25619. * @param offset defines offset in the buffer (0 by default)
  25620. * @param size defines the size in floats of attributes (position is 3 for instance)
  25621. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25622. * @param instanced defines if the vertex buffer contains indexed data
  25623. * @returns the new vertex buffer
  25624. */
  25625. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25626. // a lot of these parameters are ignored as they are overriden by the buffer
  25627. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25628. };
  25629. // Properties
  25630. Buffer.prototype.isUpdatable = function () {
  25631. return this._updatable;
  25632. };
  25633. Buffer.prototype.getData = function () {
  25634. return this._data;
  25635. };
  25636. Buffer.prototype.getBuffer = function () {
  25637. return this._buffer;
  25638. };
  25639. Buffer.prototype.getStrideSize = function () {
  25640. return this._strideSize;
  25641. };
  25642. // public getIsInstanced(): boolean {
  25643. // return this._instanced;
  25644. // }
  25645. // public get instanceDivisor(): number {
  25646. // return this._instanceDivisor;
  25647. // }
  25648. // public set instanceDivisor(value: number) {
  25649. // this._instanceDivisor = value;
  25650. // if (value == 0) {
  25651. // this._instanced = false;
  25652. // } else {
  25653. // this._instanced = true;
  25654. // }
  25655. // }
  25656. // Methods
  25657. Buffer.prototype.create = function (data) {
  25658. if (data === void 0) { data = null; }
  25659. if (!data && this._buffer) {
  25660. return; // nothing to do
  25661. }
  25662. data = data || this._data;
  25663. if (!data) {
  25664. return;
  25665. }
  25666. if (!this._buffer) {
  25667. if (this._updatable) {
  25668. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25669. this._data = data;
  25670. }
  25671. else {
  25672. this._buffer = this._engine.createVertexBuffer(data);
  25673. }
  25674. }
  25675. else if (this._updatable) {
  25676. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25677. this._data = data;
  25678. }
  25679. };
  25680. Buffer.prototype._rebuild = function () {
  25681. this._buffer = null;
  25682. this.create(this._data);
  25683. };
  25684. Buffer.prototype.update = function (data) {
  25685. this.create(data);
  25686. };
  25687. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25688. if (!this._buffer) {
  25689. return;
  25690. }
  25691. if (this._updatable) {
  25692. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25693. this._data = null;
  25694. }
  25695. };
  25696. Buffer.prototype.dispose = function () {
  25697. if (!this._buffer) {
  25698. return;
  25699. }
  25700. if (this._engine._releaseBuffer(this._buffer)) {
  25701. this._buffer = null;
  25702. }
  25703. };
  25704. return Buffer;
  25705. }());
  25706. BABYLON.Buffer = Buffer;
  25707. })(BABYLON || (BABYLON = {}));
  25708. //# sourceMappingURL=babylon.buffer.js.map
  25709. var BABYLON;
  25710. (function (BABYLON) {
  25711. var VertexBuffer = /** @class */ (function () {
  25712. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25713. if (data instanceof BABYLON.Buffer) {
  25714. if (!stride) {
  25715. stride = data.getStrideSize();
  25716. }
  25717. this._buffer = data;
  25718. this._ownsBuffer = false;
  25719. }
  25720. else {
  25721. if (!stride) {
  25722. stride = VertexBuffer.DeduceStride(kind);
  25723. }
  25724. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25725. this._ownsBuffer = true;
  25726. }
  25727. this._stride = stride;
  25728. this._instanced = instanced !== undefined ? instanced : false;
  25729. this._instanceDivisor = instanced ? 1 : 0;
  25730. this._offset = offset ? offset : 0;
  25731. this._size = size ? size : stride;
  25732. this._kind = kind;
  25733. }
  25734. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25735. /**
  25736. * Gets or sets the instance divisor when in instanced mode
  25737. */
  25738. get: function () {
  25739. return this._instanceDivisor;
  25740. },
  25741. set: function (value) {
  25742. this._instanceDivisor = value;
  25743. if (value == 0) {
  25744. this._instanced = false;
  25745. }
  25746. else {
  25747. this._instanced = true;
  25748. }
  25749. },
  25750. enumerable: true,
  25751. configurable: true
  25752. });
  25753. VertexBuffer.prototype._rebuild = function () {
  25754. if (!this._buffer) {
  25755. return;
  25756. }
  25757. this._buffer._rebuild();
  25758. };
  25759. /**
  25760. * Returns the kind of the VertexBuffer (string).
  25761. */
  25762. VertexBuffer.prototype.getKind = function () {
  25763. return this._kind;
  25764. };
  25765. // Properties
  25766. /**
  25767. * Boolean : is the VertexBuffer updatable ?
  25768. */
  25769. VertexBuffer.prototype.isUpdatable = function () {
  25770. return this._buffer.isUpdatable();
  25771. };
  25772. /**
  25773. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25774. */
  25775. VertexBuffer.prototype.getData = function () {
  25776. return this._buffer.getData();
  25777. };
  25778. /**
  25779. * Returns the WebGLBuffer associated to the VertexBuffer.
  25780. */
  25781. VertexBuffer.prototype.getBuffer = function () {
  25782. return this._buffer.getBuffer();
  25783. };
  25784. /**
  25785. * Returns the stride of the VertexBuffer (integer).
  25786. */
  25787. VertexBuffer.prototype.getStrideSize = function () {
  25788. return this._stride;
  25789. };
  25790. /**
  25791. * Returns the offset (integer).
  25792. */
  25793. VertexBuffer.prototype.getOffset = function () {
  25794. return this._offset;
  25795. };
  25796. /**
  25797. * Returns the VertexBuffer total size (integer).
  25798. */
  25799. VertexBuffer.prototype.getSize = function () {
  25800. return this._size;
  25801. };
  25802. /**
  25803. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25804. */
  25805. VertexBuffer.prototype.getIsInstanced = function () {
  25806. return this._instanced;
  25807. };
  25808. /**
  25809. * Returns the instancing divisor, zero for non-instanced (integer).
  25810. */
  25811. VertexBuffer.prototype.getInstanceDivisor = function () {
  25812. return this._instanceDivisor;
  25813. };
  25814. // Methods
  25815. /**
  25816. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25817. * Returns the created WebGLBuffer.
  25818. */
  25819. VertexBuffer.prototype.create = function (data) {
  25820. return this._buffer.create(data);
  25821. };
  25822. /**
  25823. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25824. * This function will create a new buffer if the current one is not updatable
  25825. * Returns the updated WebGLBuffer.
  25826. */
  25827. VertexBuffer.prototype.update = function (data) {
  25828. return this._buffer.update(data);
  25829. };
  25830. /**
  25831. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25832. * Returns the directly updated WebGLBuffer.
  25833. */
  25834. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25835. return this._buffer.updateDirectly(data, offset);
  25836. };
  25837. /**
  25838. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25839. */
  25840. VertexBuffer.prototype.dispose = function () {
  25841. if (this._ownsBuffer) {
  25842. this._buffer.dispose();
  25843. }
  25844. };
  25845. Object.defineProperty(VertexBuffer, "PositionKind", {
  25846. get: function () {
  25847. return VertexBuffer._PositionKind;
  25848. },
  25849. enumerable: true,
  25850. configurable: true
  25851. });
  25852. Object.defineProperty(VertexBuffer, "NormalKind", {
  25853. get: function () {
  25854. return VertexBuffer._NormalKind;
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(VertexBuffer, "TangentKind", {
  25860. get: function () {
  25861. return VertexBuffer._TangentKind;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(VertexBuffer, "UVKind", {
  25867. get: function () {
  25868. return VertexBuffer._UVKind;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25874. get: function () {
  25875. return VertexBuffer._UV2Kind;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25881. get: function () {
  25882. return VertexBuffer._UV3Kind;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25888. get: function () {
  25889. return VertexBuffer._UV4Kind;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25895. get: function () {
  25896. return VertexBuffer._UV5Kind;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25902. get: function () {
  25903. return VertexBuffer._UV6Kind;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(VertexBuffer, "ColorKind", {
  25909. get: function () {
  25910. return VertexBuffer._ColorKind;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25916. get: function () {
  25917. return VertexBuffer._MatricesIndicesKind;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25923. get: function () {
  25924. return VertexBuffer._MatricesWeightsKind;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25930. get: function () {
  25931. return VertexBuffer._MatricesIndicesExtraKind;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25937. get: function () {
  25938. return VertexBuffer._MatricesWeightsExtraKind;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. /**
  25944. * Deduces the stride given a kind.
  25945. * @param kind The kind string to deduce
  25946. * @returns The deduced stride
  25947. */
  25948. VertexBuffer.DeduceStride = function (kind) {
  25949. switch (kind) {
  25950. case VertexBuffer.UVKind:
  25951. case VertexBuffer.UV2Kind:
  25952. case VertexBuffer.UV3Kind:
  25953. case VertexBuffer.UV4Kind:
  25954. case VertexBuffer.UV5Kind:
  25955. case VertexBuffer.UV6Kind:
  25956. return 2;
  25957. case VertexBuffer.NormalKind:
  25958. case VertexBuffer.PositionKind:
  25959. return 3;
  25960. case VertexBuffer.ColorKind:
  25961. case VertexBuffer.MatricesIndicesKind:
  25962. case VertexBuffer.MatricesIndicesExtraKind:
  25963. case VertexBuffer.MatricesWeightsKind:
  25964. case VertexBuffer.MatricesWeightsExtraKind:
  25965. case VertexBuffer.TangentKind:
  25966. return 4;
  25967. default:
  25968. throw new Error("Invalid kind '" + kind + "'");
  25969. }
  25970. };
  25971. // Enums
  25972. VertexBuffer._PositionKind = "position";
  25973. VertexBuffer._NormalKind = "normal";
  25974. VertexBuffer._TangentKind = "tangent";
  25975. VertexBuffer._UVKind = "uv";
  25976. VertexBuffer._UV2Kind = "uv2";
  25977. VertexBuffer._UV3Kind = "uv3";
  25978. VertexBuffer._UV4Kind = "uv4";
  25979. VertexBuffer._UV5Kind = "uv5";
  25980. VertexBuffer._UV6Kind = "uv6";
  25981. VertexBuffer._ColorKind = "color";
  25982. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25983. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25984. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25985. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25986. return VertexBuffer;
  25987. }());
  25988. BABYLON.VertexBuffer = VertexBuffer;
  25989. })(BABYLON || (BABYLON = {}));
  25990. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25991. var BABYLON;
  25992. (function (BABYLON) {
  25993. /**
  25994. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25995. */
  25996. var DummyInternalTextureTracker = /** @class */ (function () {
  25997. function DummyInternalTextureTracker() {
  25998. /**
  25999. * Gets or set the previous tracker in the list
  26000. */
  26001. this.previous = null;
  26002. /**
  26003. * Gets or set the next tracker in the list
  26004. */
  26005. this.next = null;
  26006. }
  26007. return DummyInternalTextureTracker;
  26008. }());
  26009. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26010. })(BABYLON || (BABYLON = {}));
  26011. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26012. var BABYLON;
  26013. (function (BABYLON) {
  26014. /**
  26015. * Class used to store data associated with WebGL texture data for the engine
  26016. * This class should not be used directly
  26017. */
  26018. var InternalTexture = /** @class */ (function () {
  26019. /**
  26020. * Creates a new InternalTexture
  26021. * @param engine defines the engine to use
  26022. * @param dataSource defines the type of data that will be used
  26023. */
  26024. function InternalTexture(engine, dataSource) {
  26025. /**
  26026. * Observable called when the texture is loaded
  26027. */
  26028. this.onLoadedObservable = new BABYLON.Observable();
  26029. /**
  26030. * Gets or set the previous tracker in the list
  26031. */
  26032. this.previous = null;
  26033. /**
  26034. * Gets or set the next tracker in the list
  26035. */
  26036. this.next = null;
  26037. // Private
  26038. /** @ignore */
  26039. this._initialSlot = -1;
  26040. /** @ignore */
  26041. this._designatedSlot = -1;
  26042. /** @ignore */
  26043. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26044. /** @ignore */
  26045. this._comparisonFunction = 0;
  26046. /** @ignore */
  26047. this._references = 1;
  26048. this._engine = engine;
  26049. this._dataSource = dataSource;
  26050. this._webGLTexture = engine._createTexture();
  26051. }
  26052. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26053. /**
  26054. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26055. */
  26056. get: function () {
  26057. return this._dataSource;
  26058. },
  26059. enumerable: true,
  26060. configurable: true
  26061. });
  26062. /**
  26063. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26064. */
  26065. InternalTexture.prototype.incrementReferences = function () {
  26066. this._references++;
  26067. };
  26068. /**
  26069. * Change the size of the texture (not the size of the content)
  26070. * @param width defines the new width
  26071. * @param height defines the new height
  26072. * @param depth defines the new depth (1 by default)
  26073. */
  26074. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26075. if (depth === void 0) { depth = 1; }
  26076. this.width = width;
  26077. this.height = height;
  26078. this.depth = depth;
  26079. this.baseWidth = width;
  26080. this.baseHeight = height;
  26081. this.baseDepth = depth;
  26082. this._size = width * height * depth;
  26083. };
  26084. /** @ignore */
  26085. InternalTexture.prototype._rebuild = function () {
  26086. var _this = this;
  26087. var proxy;
  26088. this.isReady = false;
  26089. this._cachedCoordinatesMode = null;
  26090. this._cachedWrapU = null;
  26091. this._cachedWrapV = null;
  26092. this._cachedAnisotropicFilteringLevel = null;
  26093. switch (this._dataSource) {
  26094. case InternalTexture.DATASOURCE_TEMP:
  26095. return;
  26096. case InternalTexture.DATASOURCE_URL:
  26097. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26098. _this.isReady = true;
  26099. }, null, this._buffer, undefined, this.format);
  26100. proxy._swapAndDie(this);
  26101. return;
  26102. case InternalTexture.DATASOURCE_RAW:
  26103. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26104. proxy._swapAndDie(this);
  26105. this.isReady = true;
  26106. return;
  26107. case InternalTexture.DATASOURCE_RAW3D:
  26108. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26109. proxy._swapAndDie(this);
  26110. this.isReady = true;
  26111. return;
  26112. case InternalTexture.DATASOURCE_DYNAMIC:
  26113. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26114. proxy._swapAndDie(this);
  26115. // The engine will make sure to update content so no need to flag it as isReady = true
  26116. return;
  26117. case InternalTexture.DATASOURCE_RENDERTARGET:
  26118. var options = new BABYLON.RenderTargetCreationOptions();
  26119. options.generateDepthBuffer = this._generateDepthBuffer;
  26120. options.generateMipMaps = this.generateMipMaps;
  26121. options.generateStencilBuffer = this._generateStencilBuffer;
  26122. options.samplingMode = this.samplingMode;
  26123. options.type = this.type;
  26124. if (this.isCube) {
  26125. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26126. }
  26127. else {
  26128. var size = {
  26129. width: this.width,
  26130. height: this.height
  26131. };
  26132. proxy = this._engine.createRenderTargetTexture(size, options);
  26133. }
  26134. proxy._swapAndDie(this);
  26135. this.isReady = true;
  26136. return;
  26137. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26138. var depthTextureOptions = {
  26139. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26140. comparisonFunction: this._comparisonFunction,
  26141. generateStencil: this._generateStencilBuffer,
  26142. };
  26143. if (this.isCube) {
  26144. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26145. }
  26146. else {
  26147. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26148. }
  26149. proxy._swapAndDie(this);
  26150. this.isReady = true;
  26151. return;
  26152. case InternalTexture.DATASOURCE_CUBE:
  26153. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26154. _this.isReady = true;
  26155. }, null, this.format, this._extension);
  26156. proxy._swapAndDie(this);
  26157. return;
  26158. case InternalTexture.DATASOURCE_CUBERAW:
  26159. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26160. proxy._swapAndDie(this);
  26161. this.isReady = true;
  26162. return;
  26163. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26164. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26165. if (proxy) {
  26166. proxy._swapAndDie(_this);
  26167. }
  26168. _this.isReady = true;
  26169. }, null, this.format, this._extension);
  26170. return;
  26171. }
  26172. };
  26173. InternalTexture.prototype._swapAndDie = function (target) {
  26174. target._webGLTexture = this._webGLTexture;
  26175. if (this._framebuffer) {
  26176. target._framebuffer = this._framebuffer;
  26177. }
  26178. if (this._depthStencilBuffer) {
  26179. target._depthStencilBuffer = this._depthStencilBuffer;
  26180. }
  26181. if (this._lodTextureHigh) {
  26182. if (target._lodTextureHigh) {
  26183. target._lodTextureHigh.dispose();
  26184. }
  26185. target._lodTextureHigh = this._lodTextureHigh;
  26186. }
  26187. if (this._lodTextureMid) {
  26188. if (target._lodTextureMid) {
  26189. target._lodTextureMid.dispose();
  26190. }
  26191. target._lodTextureMid = this._lodTextureMid;
  26192. }
  26193. if (this._lodTextureLow) {
  26194. if (target._lodTextureLow) {
  26195. target._lodTextureLow.dispose();
  26196. }
  26197. target._lodTextureLow = this._lodTextureLow;
  26198. }
  26199. var cache = this._engine.getLoadedTexturesCache();
  26200. var index = cache.indexOf(this);
  26201. if (index !== -1) {
  26202. cache.splice(index, 1);
  26203. }
  26204. };
  26205. /**
  26206. * Dispose the current allocated resources
  26207. */
  26208. InternalTexture.prototype.dispose = function () {
  26209. if (!this._webGLTexture) {
  26210. return;
  26211. }
  26212. this._references--;
  26213. if (this._references === 0) {
  26214. this._engine._releaseTexture(this);
  26215. this._webGLTexture = null;
  26216. this.previous = null;
  26217. this.next = null;
  26218. }
  26219. };
  26220. /**
  26221. * The source of the texture data is unknown
  26222. */
  26223. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26224. /**
  26225. * Texture data comes from an URL
  26226. */
  26227. InternalTexture.DATASOURCE_URL = 1;
  26228. /**
  26229. * Texture data is only used for temporary storage
  26230. */
  26231. InternalTexture.DATASOURCE_TEMP = 2;
  26232. /**
  26233. * Texture data comes from raw data (ArrayBuffer)
  26234. */
  26235. InternalTexture.DATASOURCE_RAW = 3;
  26236. /**
  26237. * Texture content is dynamic (video or dynamic texture)
  26238. */
  26239. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26240. /**
  26241. * Texture content is generated by rendering to it
  26242. */
  26243. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26244. /**
  26245. * Texture content is part of a multi render target process
  26246. */
  26247. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26248. /**
  26249. * Texture data comes from a cube data file
  26250. */
  26251. InternalTexture.DATASOURCE_CUBE = 7;
  26252. /**
  26253. * Texture data comes from a raw cube data
  26254. */
  26255. InternalTexture.DATASOURCE_CUBERAW = 8;
  26256. /**
  26257. * Texture data come from a prefiltered cube data file
  26258. */
  26259. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26260. /**
  26261. * Texture content is raw 3D data
  26262. */
  26263. InternalTexture.DATASOURCE_RAW3D = 10;
  26264. /**
  26265. * Texture content is a depth texture
  26266. */
  26267. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26268. return InternalTexture;
  26269. }());
  26270. BABYLON.InternalTexture = InternalTexture;
  26271. })(BABYLON || (BABYLON = {}));
  26272. //# sourceMappingURL=babylon.internalTexture.js.map
  26273. var BABYLON;
  26274. (function (BABYLON) {
  26275. var BaseTexture = /** @class */ (function () {
  26276. function BaseTexture(scene) {
  26277. this._hasAlpha = false;
  26278. this.getAlphaFromRGB = false;
  26279. this.level = 1;
  26280. this.coordinatesIndex = 0;
  26281. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26282. /**
  26283. * | Value | Type | Description |
  26284. * | ----- | ------------------ | ----------- |
  26285. * | 0 | CLAMP_ADDRESSMODE | |
  26286. * | 1 | WRAP_ADDRESSMODE | |
  26287. * | 2 | MIRROR_ADDRESSMODE | |
  26288. */
  26289. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26290. /**
  26291. * | Value | Type | Description |
  26292. * | ----- | ------------------ | ----------- |
  26293. * | 0 | CLAMP_ADDRESSMODE | |
  26294. * | 1 | WRAP_ADDRESSMODE | |
  26295. * | 2 | MIRROR_ADDRESSMODE | |
  26296. */
  26297. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26298. /**
  26299. * | Value | Type | Description |
  26300. * | ----- | ------------------ | ----------- |
  26301. * | 0 | CLAMP_ADDRESSMODE | |
  26302. * | 1 | WRAP_ADDRESSMODE | |
  26303. * | 2 | MIRROR_ADDRESSMODE | |
  26304. */
  26305. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26306. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26307. this.isCube = false;
  26308. this.is3D = false;
  26309. this.gammaSpace = true;
  26310. this.invertZ = false;
  26311. this.lodLevelInAlpha = false;
  26312. this.lodGenerationOffset = 0.0;
  26313. this.lodGenerationScale = 0.8;
  26314. this.isRenderTarget = false;
  26315. this.animations = new Array();
  26316. /**
  26317. * An event triggered when the texture is disposed.
  26318. * @type {BABYLON.Observable}
  26319. */
  26320. this.onDisposeObservable = new BABYLON.Observable();
  26321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26322. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26323. if (this._scene) {
  26324. this._scene.textures.push(this);
  26325. }
  26326. this._uid = null;
  26327. }
  26328. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26329. get: function () {
  26330. return this._hasAlpha;
  26331. },
  26332. set: function (value) {
  26333. if (this._hasAlpha === value) {
  26334. return;
  26335. }
  26336. this._hasAlpha = value;
  26337. if (this._scene) {
  26338. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26339. }
  26340. },
  26341. enumerable: true,
  26342. configurable: true
  26343. });
  26344. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26345. get: function () {
  26346. return this._coordinatesMode;
  26347. },
  26348. /**
  26349. * How a texture is mapped.
  26350. *
  26351. * | Value | Type | Description |
  26352. * | ----- | ----------------------------------- | ----------- |
  26353. * | 0 | EXPLICIT_MODE | |
  26354. * | 1 | SPHERICAL_MODE | |
  26355. * | 2 | PLANAR_MODE | |
  26356. * | 3 | CUBIC_MODE | |
  26357. * | 4 | PROJECTION_MODE | |
  26358. * | 5 | SKYBOX_MODE | |
  26359. * | 6 | INVCUBIC_MODE | |
  26360. * | 7 | EQUIRECTANGULAR_MODE | |
  26361. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26362. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26363. */
  26364. set: function (value) {
  26365. if (this._coordinatesMode === value) {
  26366. return;
  26367. }
  26368. this._coordinatesMode = value;
  26369. if (this._scene) {
  26370. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26371. }
  26372. },
  26373. enumerable: true,
  26374. configurable: true
  26375. });
  26376. Object.defineProperty(BaseTexture.prototype, "uid", {
  26377. get: function () {
  26378. if (!this._uid) {
  26379. this._uid = BABYLON.Tools.RandomId();
  26380. }
  26381. return this._uid;
  26382. },
  26383. enumerable: true,
  26384. configurable: true
  26385. });
  26386. BaseTexture.prototype.toString = function () {
  26387. return this.name;
  26388. };
  26389. BaseTexture.prototype.getClassName = function () {
  26390. return "BaseTexture";
  26391. };
  26392. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26393. set: function (callback) {
  26394. if (this._onDisposeObserver) {
  26395. this.onDisposeObservable.remove(this._onDisposeObserver);
  26396. }
  26397. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26398. },
  26399. enumerable: true,
  26400. configurable: true
  26401. });
  26402. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26403. get: function () {
  26404. return true;
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. BaseTexture.prototype.getScene = function () {
  26410. return this._scene;
  26411. };
  26412. BaseTexture.prototype.getTextureMatrix = function () {
  26413. return BABYLON.Matrix.IdentityReadOnly;
  26414. };
  26415. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26416. return BABYLON.Matrix.IdentityReadOnly;
  26417. };
  26418. BaseTexture.prototype.getInternalTexture = function () {
  26419. return this._texture;
  26420. };
  26421. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26422. return !this.isBlocking || this.isReady();
  26423. };
  26424. BaseTexture.prototype.isReady = function () {
  26425. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26426. this.delayLoad();
  26427. return false;
  26428. }
  26429. if (this._texture) {
  26430. return this._texture.isReady;
  26431. }
  26432. return false;
  26433. };
  26434. BaseTexture.prototype.getSize = function () {
  26435. if (this._texture && this._texture.width) {
  26436. return new BABYLON.Size(this._texture.width, this._texture.height);
  26437. }
  26438. if (this._texture && this._texture._size) {
  26439. return new BABYLON.Size(this._texture._size, this._texture._size);
  26440. }
  26441. return BABYLON.Size.Zero();
  26442. };
  26443. BaseTexture.prototype.getBaseSize = function () {
  26444. if (!this.isReady() || !this._texture)
  26445. return BABYLON.Size.Zero();
  26446. if (this._texture._size) {
  26447. return new BABYLON.Size(this._texture._size, this._texture._size);
  26448. }
  26449. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26450. };
  26451. BaseTexture.prototype.scale = function (ratio) {
  26452. };
  26453. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26454. get: function () {
  26455. return false;
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26461. if (!this._scene) {
  26462. return null;
  26463. }
  26464. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26465. for (var index = 0; index < texturesCache.length; index++) {
  26466. var texturesCacheEntry = texturesCache[index];
  26467. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26468. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26469. texturesCacheEntry.incrementReferences();
  26470. return texturesCacheEntry;
  26471. }
  26472. }
  26473. }
  26474. return null;
  26475. };
  26476. BaseTexture.prototype._rebuild = function () {
  26477. };
  26478. BaseTexture.prototype.delayLoad = function () {
  26479. };
  26480. BaseTexture.prototype.clone = function () {
  26481. return null;
  26482. };
  26483. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26484. get: function () {
  26485. if (!this._texture) {
  26486. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26487. }
  26488. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26489. },
  26490. enumerable: true,
  26491. configurable: true
  26492. });
  26493. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26494. get: function () {
  26495. if (!this._texture) {
  26496. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26497. }
  26498. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26499. },
  26500. enumerable: true,
  26501. configurable: true
  26502. });
  26503. BaseTexture.prototype.readPixels = function (faceIndex) {
  26504. if (faceIndex === void 0) { faceIndex = 0; }
  26505. if (!this._texture) {
  26506. return null;
  26507. }
  26508. var size = this.getSize();
  26509. var scene = this.getScene();
  26510. if (!scene) {
  26511. return null;
  26512. }
  26513. var engine = scene.getEngine();
  26514. if (this._texture.isCube) {
  26515. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26516. }
  26517. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26518. };
  26519. BaseTexture.prototype.releaseInternalTexture = function () {
  26520. if (this._texture) {
  26521. this._texture.dispose();
  26522. this._texture = null;
  26523. }
  26524. };
  26525. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26526. get: function () {
  26527. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26528. return null;
  26529. }
  26530. if (!this._texture._sphericalPolynomial) {
  26531. this._texture._sphericalPolynomial =
  26532. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26533. }
  26534. return this._texture._sphericalPolynomial;
  26535. },
  26536. set: function (value) {
  26537. if (this._texture) {
  26538. this._texture._sphericalPolynomial = value;
  26539. }
  26540. },
  26541. enumerable: true,
  26542. configurable: true
  26543. });
  26544. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26545. get: function () {
  26546. if (this._texture) {
  26547. return this._texture._lodTextureHigh;
  26548. }
  26549. return null;
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26555. get: function () {
  26556. if (this._texture) {
  26557. return this._texture._lodTextureMid;
  26558. }
  26559. return null;
  26560. },
  26561. enumerable: true,
  26562. configurable: true
  26563. });
  26564. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26565. get: function () {
  26566. if (this._texture) {
  26567. return this._texture._lodTextureLow;
  26568. }
  26569. return null;
  26570. },
  26571. enumerable: true,
  26572. configurable: true
  26573. });
  26574. BaseTexture.prototype.dispose = function () {
  26575. if (!this._scene) {
  26576. return;
  26577. }
  26578. // Animations
  26579. this._scene.stopAnimation(this);
  26580. // Remove from scene
  26581. this._scene._removePendingData(this);
  26582. var index = this._scene.textures.indexOf(this);
  26583. if (index >= 0) {
  26584. this._scene.textures.splice(index, 1);
  26585. }
  26586. if (this._texture === undefined) {
  26587. return;
  26588. }
  26589. // Release
  26590. this.releaseInternalTexture();
  26591. // Callback
  26592. this.onDisposeObservable.notifyObservers(this);
  26593. this.onDisposeObservable.clear();
  26594. };
  26595. BaseTexture.prototype.serialize = function () {
  26596. if (!this.name) {
  26597. return null;
  26598. }
  26599. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26600. // Animations
  26601. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26602. return serializationObject;
  26603. };
  26604. BaseTexture.WhenAllReady = function (textures, callback) {
  26605. var numRemaining = textures.length;
  26606. if (numRemaining === 0) {
  26607. callback();
  26608. return;
  26609. }
  26610. var _loop_1 = function () {
  26611. texture = textures[i];
  26612. if (texture.isReady()) {
  26613. if (--numRemaining === 0) {
  26614. callback();
  26615. }
  26616. }
  26617. else {
  26618. onLoadObservable = texture.onLoadObservable;
  26619. var onLoadCallback_1 = function () {
  26620. onLoadObservable.removeCallback(onLoadCallback_1);
  26621. if (--numRemaining === 0) {
  26622. callback();
  26623. }
  26624. };
  26625. onLoadObservable.add(onLoadCallback_1);
  26626. }
  26627. };
  26628. var texture, onLoadObservable;
  26629. for (var i = 0; i < textures.length; i++) {
  26630. _loop_1();
  26631. }
  26632. };
  26633. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26634. __decorate([
  26635. BABYLON.serialize()
  26636. ], BaseTexture.prototype, "name", void 0);
  26637. __decorate([
  26638. BABYLON.serialize("hasAlpha")
  26639. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26640. __decorate([
  26641. BABYLON.serialize()
  26642. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26643. __decorate([
  26644. BABYLON.serialize()
  26645. ], BaseTexture.prototype, "level", void 0);
  26646. __decorate([
  26647. BABYLON.serialize()
  26648. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26649. __decorate([
  26650. BABYLON.serialize("coordinatesMode")
  26651. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26652. __decorate([
  26653. BABYLON.serialize()
  26654. ], BaseTexture.prototype, "wrapU", void 0);
  26655. __decorate([
  26656. BABYLON.serialize()
  26657. ], BaseTexture.prototype, "wrapV", void 0);
  26658. __decorate([
  26659. BABYLON.serialize()
  26660. ], BaseTexture.prototype, "wrapR", void 0);
  26661. __decorate([
  26662. BABYLON.serialize()
  26663. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26664. __decorate([
  26665. BABYLON.serialize()
  26666. ], BaseTexture.prototype, "isCube", void 0);
  26667. __decorate([
  26668. BABYLON.serialize()
  26669. ], BaseTexture.prototype, "is3D", void 0);
  26670. __decorate([
  26671. BABYLON.serialize()
  26672. ], BaseTexture.prototype, "gammaSpace", void 0);
  26673. __decorate([
  26674. BABYLON.serialize()
  26675. ], BaseTexture.prototype, "invertZ", void 0);
  26676. __decorate([
  26677. BABYLON.serialize()
  26678. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26679. __decorate([
  26680. BABYLON.serialize()
  26681. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26682. __decorate([
  26683. BABYLON.serialize()
  26684. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26685. __decorate([
  26686. BABYLON.serialize()
  26687. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26688. return BaseTexture;
  26689. }());
  26690. BABYLON.BaseTexture = BaseTexture;
  26691. })(BABYLON || (BABYLON = {}));
  26692. //# sourceMappingURL=babylon.baseTexture.js.map
  26693. var BABYLON;
  26694. (function (BABYLON) {
  26695. var Texture = /** @class */ (function (_super) {
  26696. __extends(Texture, _super);
  26697. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26698. if (noMipmap === void 0) { noMipmap = false; }
  26699. if (invertY === void 0) { invertY = true; }
  26700. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26701. if (onLoad === void 0) { onLoad = null; }
  26702. if (onError === void 0) { onError = null; }
  26703. if (buffer === void 0) { buffer = null; }
  26704. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26705. var _this = _super.call(this, scene) || this;
  26706. _this.uOffset = 0;
  26707. _this.vOffset = 0;
  26708. _this.uScale = 1.0;
  26709. _this.vScale = 1.0;
  26710. _this.uAng = 0;
  26711. _this.vAng = 0;
  26712. _this.wAng = 0;
  26713. _this._isBlocking = true;
  26714. _this.name = url || "";
  26715. _this.url = url;
  26716. _this._noMipmap = noMipmap;
  26717. _this._invertY = invertY;
  26718. _this._samplingMode = samplingMode;
  26719. _this._buffer = buffer;
  26720. _this._deleteBuffer = deleteBuffer;
  26721. if (format) {
  26722. _this._format = format;
  26723. }
  26724. scene = _this.getScene();
  26725. if (!scene) {
  26726. return _this;
  26727. }
  26728. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26729. var load = function () {
  26730. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26731. _this.onLoadObservable.notifyObservers(_this);
  26732. }
  26733. if (onLoad) {
  26734. onLoad();
  26735. }
  26736. if (!_this.isBlocking && scene) {
  26737. scene.resetCachedMaterial();
  26738. }
  26739. };
  26740. if (!_this.url) {
  26741. _this._delayedOnLoad = load;
  26742. _this._delayedOnError = onError;
  26743. return _this;
  26744. }
  26745. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26746. if (!_this._texture) {
  26747. if (!scene.useDelayedTextureLoading) {
  26748. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26749. if (deleteBuffer) {
  26750. delete _this._buffer;
  26751. }
  26752. }
  26753. else {
  26754. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26755. _this._delayedOnLoad = load;
  26756. _this._delayedOnError = onError;
  26757. }
  26758. }
  26759. else {
  26760. if (_this._texture.isReady) {
  26761. BABYLON.Tools.SetImmediate(function () { return load(); });
  26762. }
  26763. else {
  26764. _this._texture.onLoadedObservable.add(load);
  26765. }
  26766. }
  26767. return _this;
  26768. }
  26769. Object.defineProperty(Texture.prototype, "noMipmap", {
  26770. get: function () {
  26771. return this._noMipmap;
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. Object.defineProperty(Texture.prototype, "isBlocking", {
  26777. get: function () {
  26778. return this._isBlocking;
  26779. },
  26780. set: function (value) {
  26781. this._isBlocking = value;
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(Texture.prototype, "samplingMode", {
  26787. get: function () {
  26788. return this._samplingMode;
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. Texture.prototype.updateURL = function (url) {
  26794. this.url = url;
  26795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26796. this.delayLoad();
  26797. };
  26798. Texture.prototype.delayLoad = function () {
  26799. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26800. return;
  26801. }
  26802. var scene = this.getScene();
  26803. if (!scene) {
  26804. return;
  26805. }
  26806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26807. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26808. if (!this._texture) {
  26809. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26810. if (this._deleteBuffer) {
  26811. delete this._buffer;
  26812. }
  26813. }
  26814. else {
  26815. if (this._delayedOnLoad) {
  26816. if (this._texture.isReady) {
  26817. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26818. }
  26819. else {
  26820. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26821. }
  26822. }
  26823. }
  26824. this._delayedOnLoad = null;
  26825. this._delayedOnError = null;
  26826. };
  26827. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26828. if (!this._texture) {
  26829. return;
  26830. }
  26831. var scene = this.getScene();
  26832. if (!scene) {
  26833. return;
  26834. }
  26835. this._samplingMode = samplingMode;
  26836. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26837. };
  26838. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26839. x *= this.uScale;
  26840. y *= this.vScale;
  26841. x -= 0.5 * this.uScale;
  26842. y -= 0.5 * this.vScale;
  26843. z -= 0.5;
  26844. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26845. t.x += 0.5 * this.uScale + this.uOffset;
  26846. t.y += 0.5 * this.vScale + this.vOffset;
  26847. t.z += 0.5;
  26848. };
  26849. Texture.prototype.getTextureMatrix = function () {
  26850. var _this = this;
  26851. if (this.uOffset === this._cachedUOffset &&
  26852. this.vOffset === this._cachedVOffset &&
  26853. this.uScale === this._cachedUScale &&
  26854. this.vScale === this._cachedVScale &&
  26855. this.uAng === this._cachedUAng &&
  26856. this.vAng === this._cachedVAng &&
  26857. this.wAng === this._cachedWAng) {
  26858. return this._cachedTextureMatrix;
  26859. }
  26860. this._cachedUOffset = this.uOffset;
  26861. this._cachedVOffset = this.vOffset;
  26862. this._cachedUScale = this.uScale;
  26863. this._cachedVScale = this.vScale;
  26864. this._cachedUAng = this.uAng;
  26865. this._cachedVAng = this.vAng;
  26866. this._cachedWAng = this.wAng;
  26867. if (!this._cachedTextureMatrix) {
  26868. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26869. this._rowGenerationMatrix = new BABYLON.Matrix();
  26870. this._t0 = BABYLON.Vector3.Zero();
  26871. this._t1 = BABYLON.Vector3.Zero();
  26872. this._t2 = BABYLON.Vector3.Zero();
  26873. }
  26874. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26875. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26876. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26877. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26878. this._t1.subtractInPlace(this._t0);
  26879. this._t2.subtractInPlace(this._t0);
  26880. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26881. this._cachedTextureMatrix.m[0] = this._t1.x;
  26882. this._cachedTextureMatrix.m[1] = this._t1.y;
  26883. this._cachedTextureMatrix.m[2] = this._t1.z;
  26884. this._cachedTextureMatrix.m[4] = this._t2.x;
  26885. this._cachedTextureMatrix.m[5] = this._t2.y;
  26886. this._cachedTextureMatrix.m[6] = this._t2.z;
  26887. this._cachedTextureMatrix.m[8] = this._t0.x;
  26888. this._cachedTextureMatrix.m[9] = this._t0.y;
  26889. this._cachedTextureMatrix.m[10] = this._t0.z;
  26890. var scene = this.getScene();
  26891. if (!scene) {
  26892. return this._cachedTextureMatrix;
  26893. }
  26894. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26895. return mat.hasTexture(_this);
  26896. });
  26897. return this._cachedTextureMatrix;
  26898. };
  26899. Texture.prototype.getReflectionTextureMatrix = function () {
  26900. var _this = this;
  26901. var scene = this.getScene();
  26902. if (!scene) {
  26903. return this._cachedTextureMatrix;
  26904. }
  26905. if (this.uOffset === this._cachedUOffset &&
  26906. this.vOffset === this._cachedVOffset &&
  26907. this.uScale === this._cachedUScale &&
  26908. this.vScale === this._cachedVScale &&
  26909. this.coordinatesMode === this._cachedCoordinatesMode) {
  26910. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26911. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26912. return this._cachedTextureMatrix;
  26913. }
  26914. }
  26915. else {
  26916. return this._cachedTextureMatrix;
  26917. }
  26918. }
  26919. if (!this._cachedTextureMatrix) {
  26920. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26921. }
  26922. if (!this._projectionModeMatrix) {
  26923. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26924. }
  26925. this._cachedUOffset = this.uOffset;
  26926. this._cachedVOffset = this.vOffset;
  26927. this._cachedUScale = this.uScale;
  26928. this._cachedVScale = this.vScale;
  26929. this._cachedCoordinatesMode = this.coordinatesMode;
  26930. switch (this.coordinatesMode) {
  26931. case Texture.PLANAR_MODE:
  26932. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26933. this._cachedTextureMatrix[0] = this.uScale;
  26934. this._cachedTextureMatrix[5] = this.vScale;
  26935. this._cachedTextureMatrix[12] = this.uOffset;
  26936. this._cachedTextureMatrix[13] = this.vOffset;
  26937. break;
  26938. case Texture.PROJECTION_MODE:
  26939. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26940. this._projectionModeMatrix.m[0] = 0.5;
  26941. this._projectionModeMatrix.m[5] = -0.5;
  26942. this._projectionModeMatrix.m[10] = 0.0;
  26943. this._projectionModeMatrix.m[12] = 0.5;
  26944. this._projectionModeMatrix.m[13] = 0.5;
  26945. this._projectionModeMatrix.m[14] = 1.0;
  26946. this._projectionModeMatrix.m[15] = 1.0;
  26947. var projectionMatrix = scene.getProjectionMatrix();
  26948. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26949. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26950. break;
  26951. default:
  26952. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26953. break;
  26954. }
  26955. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26956. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26957. });
  26958. return this._cachedTextureMatrix;
  26959. };
  26960. Texture.prototype.clone = function () {
  26961. var _this = this;
  26962. return BABYLON.SerializationHelper.Clone(function () {
  26963. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26964. }, this);
  26965. };
  26966. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26967. get: function () {
  26968. if (!this._onLoadObservable) {
  26969. this._onLoadObservable = new BABYLON.Observable();
  26970. }
  26971. return this._onLoadObservable;
  26972. },
  26973. enumerable: true,
  26974. configurable: true
  26975. });
  26976. Texture.prototype.serialize = function () {
  26977. var serializationObject = _super.prototype.serialize.call(this);
  26978. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26979. serializationObject.base64String = this._buffer;
  26980. serializationObject.name = serializationObject.name.replace("data:", "");
  26981. }
  26982. return serializationObject;
  26983. };
  26984. Texture.prototype.getClassName = function () {
  26985. return "Texture";
  26986. };
  26987. Texture.prototype.dispose = function () {
  26988. _super.prototype.dispose.call(this);
  26989. if (this.onLoadObservable) {
  26990. this.onLoadObservable.clear();
  26991. this._onLoadObservable = null;
  26992. }
  26993. this._delayedOnLoad = null;
  26994. this._delayedOnError = null;
  26995. };
  26996. // Statics
  26997. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26998. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26999. if (onLoad === void 0) { onLoad = null; }
  27000. if (onError === void 0) { onError = null; }
  27001. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27002. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27003. };
  27004. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27005. if (parsedTexture.customType) {
  27006. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27007. // Update Sampling Mode
  27008. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27009. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27010. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27011. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27012. }
  27013. }
  27014. return parsedCustomTexture;
  27015. }
  27016. if (parsedTexture.isCube) {
  27017. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27018. }
  27019. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27020. return null;
  27021. }
  27022. var texture = BABYLON.SerializationHelper.Parse(function () {
  27023. var generateMipMaps = true;
  27024. if (parsedTexture.noMipmap) {
  27025. generateMipMaps = false;
  27026. }
  27027. if (parsedTexture.mirrorPlane) {
  27028. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27029. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27030. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27031. return mirrorTexture;
  27032. }
  27033. else if (parsedTexture.isRenderTarget) {
  27034. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27035. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27036. return renderTargetTexture;
  27037. }
  27038. else {
  27039. var texture;
  27040. if (parsedTexture.base64String) {
  27041. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27042. }
  27043. else {
  27044. var url = rootUrl + parsedTexture.name;
  27045. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27046. url = parsedTexture.url;
  27047. }
  27048. texture = new Texture(url, scene, !generateMipMaps);
  27049. }
  27050. return texture;
  27051. }
  27052. }, parsedTexture, scene);
  27053. // Update Sampling Mode
  27054. if (parsedTexture.samplingMode) {
  27055. var sampling = parsedTexture.samplingMode;
  27056. if (texture._samplingMode !== sampling) {
  27057. texture.updateSamplingMode(sampling);
  27058. }
  27059. }
  27060. // Animations
  27061. if (parsedTexture.animations) {
  27062. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27063. var parsedAnimation = parsedTexture.animations[animationIndex];
  27064. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27065. }
  27066. }
  27067. return texture;
  27068. };
  27069. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27070. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27071. if (noMipmap === void 0) { noMipmap = false; }
  27072. if (invertY === void 0) { invertY = true; }
  27073. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27074. if (onLoad === void 0) { onLoad = null; }
  27075. if (onError === void 0) { onError = null; }
  27076. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27077. if (name.substr(0, 5) !== "data:") {
  27078. name = "data:" + name;
  27079. }
  27080. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27081. };
  27082. // Constants
  27083. Texture.NEAREST_SAMPLINGMODE = 1;
  27084. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27085. Texture.BILINEAR_SAMPLINGMODE = 2;
  27086. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27087. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27088. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27089. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27090. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27091. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27092. Texture.NEAREST_LINEAR = 7;
  27093. Texture.NEAREST_NEAREST = 8;
  27094. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27095. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27096. Texture.LINEAR_LINEAR = 11;
  27097. Texture.LINEAR_NEAREST = 12;
  27098. Texture.EXPLICIT_MODE = 0;
  27099. Texture.SPHERICAL_MODE = 1;
  27100. Texture.PLANAR_MODE = 2;
  27101. Texture.CUBIC_MODE = 3;
  27102. Texture.PROJECTION_MODE = 4;
  27103. Texture.SKYBOX_MODE = 5;
  27104. Texture.INVCUBIC_MODE = 6;
  27105. Texture.EQUIRECTANGULAR_MODE = 7;
  27106. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27107. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27108. Texture.CLAMP_ADDRESSMODE = 0;
  27109. Texture.WRAP_ADDRESSMODE = 1;
  27110. Texture.MIRROR_ADDRESSMODE = 2;
  27111. /**
  27112. * 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
  27113. */
  27114. Texture.UseSerializedUrlIfAny = false;
  27115. __decorate([
  27116. BABYLON.serialize()
  27117. ], Texture.prototype, "url", void 0);
  27118. __decorate([
  27119. BABYLON.serialize()
  27120. ], Texture.prototype, "uOffset", void 0);
  27121. __decorate([
  27122. BABYLON.serialize()
  27123. ], Texture.prototype, "vOffset", void 0);
  27124. __decorate([
  27125. BABYLON.serialize()
  27126. ], Texture.prototype, "uScale", void 0);
  27127. __decorate([
  27128. BABYLON.serialize()
  27129. ], Texture.prototype, "vScale", void 0);
  27130. __decorate([
  27131. BABYLON.serialize()
  27132. ], Texture.prototype, "uAng", void 0);
  27133. __decorate([
  27134. BABYLON.serialize()
  27135. ], Texture.prototype, "vAng", void 0);
  27136. __decorate([
  27137. BABYLON.serialize()
  27138. ], Texture.prototype, "wAng", void 0);
  27139. __decorate([
  27140. BABYLON.serialize()
  27141. ], Texture.prototype, "isBlocking", null);
  27142. return Texture;
  27143. }(BABYLON.BaseTexture));
  27144. BABYLON.Texture = Texture;
  27145. })(BABYLON || (BABYLON = {}));
  27146. //# sourceMappingURL=babylon.texture.js.map
  27147. var BABYLON;
  27148. (function (BABYLON) {
  27149. var _InstancesBatch = /** @class */ (function () {
  27150. function _InstancesBatch() {
  27151. this.mustReturn = false;
  27152. this.visibleInstances = new Array();
  27153. this.renderSelf = new Array();
  27154. }
  27155. return _InstancesBatch;
  27156. }());
  27157. BABYLON._InstancesBatch = _InstancesBatch;
  27158. var Mesh = /** @class */ (function (_super) {
  27159. __extends(Mesh, _super);
  27160. /**
  27161. * @constructor
  27162. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27163. * @param {Scene} scene The scene to add this mesh to.
  27164. * @param {Node} parent The parent of this mesh, if it has one
  27165. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27166. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27167. * When false, achieved by calling a clone(), also passing False.
  27168. * This will make creation of children, recursive.
  27169. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27170. */
  27171. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27172. if (scene === void 0) { scene = null; }
  27173. if (parent === void 0) { parent = null; }
  27174. if (source === void 0) { source = null; }
  27175. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27176. var _this = _super.call(this, name, scene) || this;
  27177. // Events
  27178. /**
  27179. * An event triggered before rendering the mesh
  27180. * @type {BABYLON.Observable}
  27181. */
  27182. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27183. /**
  27184. * An event triggered after rendering the mesh
  27185. * @type {BABYLON.Observable}
  27186. */
  27187. _this.onAfterRenderObservable = new BABYLON.Observable();
  27188. /**
  27189. * An event triggered before drawing the mesh
  27190. * @type {BABYLON.Observable}
  27191. */
  27192. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27193. // Members
  27194. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27195. _this.instances = new Array();
  27196. _this._LODLevels = new Array();
  27197. _this._visibleInstances = {};
  27198. _this._renderIdForInstances = new Array();
  27199. _this._batchCache = new _InstancesBatch();
  27200. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27201. // Use by builder only to know what orientation were the mesh build in.
  27202. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27203. _this.overrideMaterialSideOrientation = null;
  27204. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27205. // Will be used to save a source mesh reference, If any
  27206. _this._source = null;
  27207. scene = _this.getScene();
  27208. if (source) {
  27209. // Source mesh
  27210. _this._source = source;
  27211. // Geometry
  27212. if (source._geometry) {
  27213. source._geometry.applyToMesh(_this);
  27214. }
  27215. // Deep copy
  27216. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27217. // Metadata
  27218. if (source.metadata && source.metadata.clone) {
  27219. _this.metadata = source.metadata.clone();
  27220. }
  27221. else {
  27222. _this.metadata = source.metadata;
  27223. }
  27224. // Tags
  27225. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27226. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27227. }
  27228. // Parent
  27229. _this.parent = source.parent;
  27230. // Pivot
  27231. _this.setPivotMatrix(source.getPivotMatrix());
  27232. _this.id = name + "." + source.id;
  27233. // Material
  27234. _this.material = source.material;
  27235. var index;
  27236. if (!doNotCloneChildren) {
  27237. // Children
  27238. var directDescendants = source.getDescendants(true);
  27239. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27240. var child = directDescendants[index_1];
  27241. if (child.clone) {
  27242. child.clone(name + "." + child.name, _this);
  27243. }
  27244. }
  27245. }
  27246. // Physics clone
  27247. var physicsEngine = _this.getScene().getPhysicsEngine();
  27248. if (clonePhysicsImpostor && physicsEngine) {
  27249. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27250. if (impostor) {
  27251. _this.physicsImpostor = impostor.clone(_this);
  27252. }
  27253. }
  27254. // Particles
  27255. for (index = 0; index < scene.particleSystems.length; index++) {
  27256. var system = scene.particleSystems[index];
  27257. if (system.emitter === source) {
  27258. system.clone(system.name, _this);
  27259. }
  27260. }
  27261. _this.computeWorldMatrix(true);
  27262. }
  27263. // Parent
  27264. if (parent !== null) {
  27265. _this.parent = parent;
  27266. }
  27267. return _this;
  27268. }
  27269. Object.defineProperty(Mesh, "FRONTSIDE", {
  27270. /**
  27271. * Mesh side orientation : usually the external or front surface
  27272. */
  27273. get: function () {
  27274. return Mesh._FRONTSIDE;
  27275. },
  27276. enumerable: true,
  27277. configurable: true
  27278. });
  27279. Object.defineProperty(Mesh, "BACKSIDE", {
  27280. /**
  27281. * Mesh side orientation : usually the internal or back surface
  27282. */
  27283. get: function () {
  27284. return Mesh._BACKSIDE;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27290. /**
  27291. * Mesh side orientation : both internal and external or front and back surfaces
  27292. */
  27293. get: function () {
  27294. return Mesh._DOUBLESIDE;
  27295. },
  27296. enumerable: true,
  27297. configurable: true
  27298. });
  27299. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27300. /**
  27301. * Mesh side orientation : by default, `FRONTSIDE`
  27302. */
  27303. get: function () {
  27304. return Mesh._DEFAULTSIDE;
  27305. },
  27306. enumerable: true,
  27307. configurable: true
  27308. });
  27309. Object.defineProperty(Mesh, "NO_CAP", {
  27310. /**
  27311. * Mesh cap setting : no cap
  27312. */
  27313. get: function () {
  27314. return Mesh._NO_CAP;
  27315. },
  27316. enumerable: true,
  27317. configurable: true
  27318. });
  27319. Object.defineProperty(Mesh, "CAP_START", {
  27320. /**
  27321. * Mesh cap setting : one cap at the beginning of the mesh
  27322. */
  27323. get: function () {
  27324. return Mesh._CAP_START;
  27325. },
  27326. enumerable: true,
  27327. configurable: true
  27328. });
  27329. Object.defineProperty(Mesh, "CAP_END", {
  27330. /**
  27331. * Mesh cap setting : one cap at the end of the mesh
  27332. */
  27333. get: function () {
  27334. return Mesh._CAP_END;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Mesh, "CAP_ALL", {
  27340. /**
  27341. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27342. */
  27343. get: function () {
  27344. return Mesh._CAP_ALL;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27350. set: function (callback) {
  27351. if (this._onBeforeDrawObserver) {
  27352. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27353. }
  27354. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27355. },
  27356. enumerable: true,
  27357. configurable: true
  27358. });
  27359. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27360. get: function () {
  27361. return this._morphTargetManager;
  27362. },
  27363. set: function (value) {
  27364. if (this._morphTargetManager === value) {
  27365. return;
  27366. }
  27367. this._morphTargetManager = value;
  27368. this._syncGeometryWithMorphTargetManager();
  27369. },
  27370. enumerable: true,
  27371. configurable: true
  27372. });
  27373. Object.defineProperty(Mesh.prototype, "source", {
  27374. get: function () {
  27375. return this._source;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27381. get: function () {
  27382. return this._unIndexed;
  27383. },
  27384. set: function (value) {
  27385. if (this._unIndexed !== value) {
  27386. this._unIndexed = value;
  27387. this._markSubMeshesAsAttributesDirty();
  27388. }
  27389. },
  27390. enumerable: true,
  27391. configurable: true
  27392. });
  27393. // Methods
  27394. /**
  27395. * Returns the string "Mesh".
  27396. */
  27397. Mesh.prototype.getClassName = function () {
  27398. return "Mesh";
  27399. };
  27400. /**
  27401. * Returns a string.
  27402. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27403. */
  27404. Mesh.prototype.toString = function (fullDetails) {
  27405. var ret = _super.prototype.toString.call(this, fullDetails);
  27406. ret += ", n vertices: " + this.getTotalVertices();
  27407. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27408. if (this.animations) {
  27409. for (var i = 0; i < this.animations.length; i++) {
  27410. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27411. }
  27412. }
  27413. if (fullDetails) {
  27414. if (this._geometry) {
  27415. var ib = this.getIndices();
  27416. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27417. if (vb && ib) {
  27418. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27419. }
  27420. }
  27421. else {
  27422. ret += ", flat shading: UNKNOWN";
  27423. }
  27424. }
  27425. return ret;
  27426. };
  27427. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27428. /**
  27429. * True if the mesh has some Levels Of Details (LOD).
  27430. * Returns a boolean.
  27431. */
  27432. get: function () {
  27433. return this._LODLevels.length > 0;
  27434. },
  27435. enumerable: true,
  27436. configurable: true
  27437. });
  27438. /**
  27439. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27440. * @returns an array of {BABYLON.MeshLODLevel}
  27441. */
  27442. Mesh.prototype.getLODLevels = function () {
  27443. return this._LODLevels;
  27444. };
  27445. Mesh.prototype._sortLODLevels = function () {
  27446. this._LODLevels.sort(function (a, b) {
  27447. if (a.distance < b.distance) {
  27448. return 1;
  27449. }
  27450. if (a.distance > b.distance) {
  27451. return -1;
  27452. }
  27453. return 0;
  27454. });
  27455. };
  27456. /**
  27457. * Add a mesh as LOD level triggered at the given distance.
  27458. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27459. * @param {number} distance The distance from the center of the object to show this level
  27460. * @param {Mesh} mesh The mesh to be added as LOD level
  27461. * @return {Mesh} This mesh (for chaining)
  27462. */
  27463. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27464. if (mesh && mesh._masterMesh) {
  27465. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27466. return this;
  27467. }
  27468. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27469. this._LODLevels.push(level);
  27470. if (mesh) {
  27471. mesh._masterMesh = this;
  27472. }
  27473. this._sortLODLevels();
  27474. return this;
  27475. };
  27476. /**
  27477. * Returns the LOD level mesh at the passed distance or null if not found.
  27478. * It is related to the method `addLODLevel(distance, mesh)`.
  27479. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27480. * Returns an object Mesh or `null`.
  27481. */
  27482. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27483. for (var index = 0; index < this._LODLevels.length; index++) {
  27484. var level = this._LODLevels[index];
  27485. if (level.distance === distance) {
  27486. return level.mesh;
  27487. }
  27488. }
  27489. return null;
  27490. };
  27491. /**
  27492. * Remove a mesh from the LOD array
  27493. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27494. * @param {Mesh} mesh The mesh to be removed.
  27495. * @return {Mesh} This mesh (for chaining)
  27496. */
  27497. Mesh.prototype.removeLODLevel = function (mesh) {
  27498. for (var index = 0; index < this._LODLevels.length; index++) {
  27499. if (this._LODLevels[index].mesh === mesh) {
  27500. this._LODLevels.splice(index, 1);
  27501. if (mesh) {
  27502. mesh._masterMesh = null;
  27503. }
  27504. }
  27505. }
  27506. this._sortLODLevels();
  27507. return this;
  27508. };
  27509. /**
  27510. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27511. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27512. */
  27513. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27514. if (!this._LODLevels || this._LODLevels.length === 0) {
  27515. return this;
  27516. }
  27517. var bSphere;
  27518. if (boundingSphere) {
  27519. bSphere = boundingSphere;
  27520. }
  27521. else {
  27522. var boundingInfo = this.getBoundingInfo();
  27523. bSphere = boundingInfo.boundingSphere;
  27524. }
  27525. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27526. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27527. if (this.onLODLevelSelection) {
  27528. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27529. }
  27530. return this;
  27531. }
  27532. for (var index = 0; index < this._LODLevels.length; index++) {
  27533. var level = this._LODLevels[index];
  27534. if (level.distance < distanceToCamera) {
  27535. if (level.mesh) {
  27536. level.mesh._preActivate();
  27537. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27538. }
  27539. if (this.onLODLevelSelection) {
  27540. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27541. }
  27542. return level.mesh;
  27543. }
  27544. }
  27545. if (this.onLODLevelSelection) {
  27546. this.onLODLevelSelection(distanceToCamera, this, this);
  27547. }
  27548. return this;
  27549. };
  27550. Object.defineProperty(Mesh.prototype, "geometry", {
  27551. /**
  27552. * Returns the mesh internal Geometry object.
  27553. */
  27554. get: function () {
  27555. return this._geometry;
  27556. },
  27557. enumerable: true,
  27558. configurable: true
  27559. });
  27560. /**
  27561. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27562. */
  27563. Mesh.prototype.getTotalVertices = function () {
  27564. if (this._geometry === null || this._geometry === undefined) {
  27565. return 0;
  27566. }
  27567. return this._geometry.getTotalVertices();
  27568. };
  27569. /**
  27570. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27571. * 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.
  27572. * You can force the copy with forceCopy === true
  27573. * Returns null if the mesh has no geometry or no vertex buffer.
  27574. * Possible `kind` values :
  27575. * - BABYLON.VertexBuffer.PositionKind
  27576. * - BABYLON.VertexBuffer.UVKind
  27577. * - BABYLON.VertexBuffer.UV2Kind
  27578. * - BABYLON.VertexBuffer.UV3Kind
  27579. * - BABYLON.VertexBuffer.UV4Kind
  27580. * - BABYLON.VertexBuffer.UV5Kind
  27581. * - BABYLON.VertexBuffer.UV6Kind
  27582. * - BABYLON.VertexBuffer.ColorKind
  27583. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27584. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27585. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27586. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27587. */
  27588. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27589. if (!this._geometry) {
  27590. return null;
  27591. }
  27592. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27593. };
  27594. /**
  27595. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27596. * Returns `null` if the mesh has no geometry.
  27597. * Possible `kind` values :
  27598. * - BABYLON.VertexBuffer.PositionKind
  27599. * - BABYLON.VertexBuffer.UVKind
  27600. * - BABYLON.VertexBuffer.UV2Kind
  27601. * - BABYLON.VertexBuffer.UV3Kind
  27602. * - BABYLON.VertexBuffer.UV4Kind
  27603. * - BABYLON.VertexBuffer.UV5Kind
  27604. * - BABYLON.VertexBuffer.UV6Kind
  27605. * - BABYLON.VertexBuffer.ColorKind
  27606. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27607. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27608. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27609. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27610. */
  27611. Mesh.prototype.getVertexBuffer = function (kind) {
  27612. if (!this._geometry) {
  27613. return null;
  27614. }
  27615. return this._geometry.getVertexBuffer(kind);
  27616. };
  27617. /**
  27618. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27619. * Possible `kind` values :
  27620. * - BABYLON.VertexBuffer.PositionKind
  27621. * - BABYLON.VertexBuffer.UVKind
  27622. * - BABYLON.VertexBuffer.UV2Kind
  27623. * - BABYLON.VertexBuffer.UV3Kind
  27624. * - BABYLON.VertexBuffer.UV4Kind
  27625. * - BABYLON.VertexBuffer.UV5Kind
  27626. * - BABYLON.VertexBuffer.UV6Kind
  27627. * - BABYLON.VertexBuffer.ColorKind
  27628. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27629. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27630. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27631. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27632. */
  27633. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27634. if (!this._geometry) {
  27635. if (this._delayInfo) {
  27636. return this._delayInfo.indexOf(kind) !== -1;
  27637. }
  27638. return false;
  27639. }
  27640. return this._geometry.isVerticesDataPresent(kind);
  27641. };
  27642. /**
  27643. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27644. * Possible `kind` values :
  27645. * - BABYLON.VertexBuffer.PositionKind
  27646. * - BABYLON.VertexBuffer.UVKind
  27647. * - BABYLON.VertexBuffer.UV2Kind
  27648. * - BABYLON.VertexBuffer.UV3Kind
  27649. * - BABYLON.VertexBuffer.UV4Kind
  27650. * - BABYLON.VertexBuffer.UV5Kind
  27651. * - BABYLON.VertexBuffer.UV6Kind
  27652. * - BABYLON.VertexBuffer.ColorKind
  27653. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27654. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27655. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27656. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27657. */
  27658. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27659. if (!this._geometry) {
  27660. if (this._delayInfo) {
  27661. return this._delayInfo.indexOf(kind) !== -1;
  27662. }
  27663. return false;
  27664. }
  27665. return this._geometry.isVertexBufferUpdatable(kind);
  27666. };
  27667. /**
  27668. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27669. * Possible `kind` values :
  27670. * - BABYLON.VertexBuffer.PositionKind
  27671. * - BABYLON.VertexBuffer.UVKind
  27672. * - BABYLON.VertexBuffer.UV2Kind
  27673. * - BABYLON.VertexBuffer.UV3Kind
  27674. * - BABYLON.VertexBuffer.UV4Kind
  27675. * - BABYLON.VertexBuffer.UV5Kind
  27676. * - BABYLON.VertexBuffer.UV6Kind
  27677. * - BABYLON.VertexBuffer.ColorKind
  27678. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27679. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27680. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27681. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27682. */
  27683. Mesh.prototype.getVerticesDataKinds = function () {
  27684. if (!this._geometry) {
  27685. var result = new Array();
  27686. if (this._delayInfo) {
  27687. this._delayInfo.forEach(function (kind, index, array) {
  27688. result.push(kind);
  27689. });
  27690. }
  27691. return result;
  27692. }
  27693. return this._geometry.getVerticesDataKinds();
  27694. };
  27695. /**
  27696. * Returns a positive integer : the total number of indices in this mesh geometry.
  27697. * Returns zero if the mesh has no geometry.
  27698. */
  27699. Mesh.prototype.getTotalIndices = function () {
  27700. if (!this._geometry) {
  27701. return 0;
  27702. }
  27703. return this._geometry.getTotalIndices();
  27704. };
  27705. /**
  27706. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27707. * 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.
  27708. * Returns an empty array if the mesh has no geometry.
  27709. */
  27710. Mesh.prototype.getIndices = function (copyWhenShared) {
  27711. if (!this._geometry) {
  27712. return [];
  27713. }
  27714. return this._geometry.getIndices(copyWhenShared);
  27715. };
  27716. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27717. get: function () {
  27718. return this._masterMesh !== null && this._masterMesh !== undefined;
  27719. },
  27720. enumerable: true,
  27721. configurable: true
  27722. });
  27723. /**
  27724. * Determine if the current mesh is ready to be rendered
  27725. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27726. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27727. * @returns true if all associated assets are ready (material, textures, shaders)
  27728. */
  27729. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27730. if (completeCheck === void 0) { completeCheck = false; }
  27731. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27732. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27733. return false;
  27734. }
  27735. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27736. return false;
  27737. }
  27738. if (!this.subMeshes || this.subMeshes.length === 0) {
  27739. return true;
  27740. }
  27741. if (!completeCheck) {
  27742. return true;
  27743. }
  27744. var engine = this.getEngine();
  27745. var scene = this.getScene();
  27746. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27747. this.computeWorldMatrix();
  27748. var mat = this.material || scene.defaultMaterial;
  27749. if (mat) {
  27750. if (mat.storeEffectOnSubMeshes) {
  27751. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27752. var subMesh = _a[_i];
  27753. var effectiveMaterial = subMesh.getMaterial();
  27754. if (effectiveMaterial) {
  27755. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27756. return false;
  27757. }
  27758. }
  27759. }
  27760. }
  27761. else {
  27762. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27763. return false;
  27764. }
  27765. }
  27766. }
  27767. // Shadows
  27768. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27769. var light = _c[_b];
  27770. var generator = light.getShadowGenerator();
  27771. if (generator) {
  27772. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27773. var subMesh = _e[_d];
  27774. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27775. return false;
  27776. }
  27777. }
  27778. }
  27779. }
  27780. // LOD
  27781. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27782. var lod = _g[_f];
  27783. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27784. return false;
  27785. }
  27786. }
  27787. return true;
  27788. };
  27789. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27790. /**
  27791. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27792. * This property is pertinent only for updatable parametric shapes.
  27793. */
  27794. get: function () {
  27795. return this._areNormalsFrozen;
  27796. },
  27797. enumerable: true,
  27798. configurable: true
  27799. });
  27800. /**
  27801. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27802. * It has no effect at all on other shapes.
  27803. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27804. * Returns the Mesh.
  27805. */
  27806. Mesh.prototype.freezeNormals = function () {
  27807. this._areNormalsFrozen = true;
  27808. return this;
  27809. };
  27810. /**
  27811. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27812. * It has no effect at all on other shapes.
  27813. * It reactivates the mesh normals computation if it was previously frozen.
  27814. * Returns the Mesh.
  27815. */
  27816. Mesh.prototype.unfreezeNormals = function () {
  27817. this._areNormalsFrozen = false;
  27818. return this;
  27819. };
  27820. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27821. /**
  27822. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27823. */
  27824. set: function (count) {
  27825. this._overridenInstanceCount = count;
  27826. },
  27827. enumerable: true,
  27828. configurable: true
  27829. });
  27830. // Methods
  27831. Mesh.prototype._preActivate = function () {
  27832. var sceneRenderId = this.getScene().getRenderId();
  27833. if (this._preActivateId === sceneRenderId) {
  27834. return this;
  27835. }
  27836. this._preActivateId = sceneRenderId;
  27837. this._visibleInstances = null;
  27838. return this;
  27839. };
  27840. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27841. if (this._visibleInstances) {
  27842. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27843. }
  27844. return this;
  27845. };
  27846. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27847. if (!this._visibleInstances) {
  27848. this._visibleInstances = {};
  27849. this._visibleInstances.defaultRenderId = renderId;
  27850. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27851. }
  27852. if (!this._visibleInstances[renderId]) {
  27853. this._visibleInstances[renderId] = new Array();
  27854. }
  27855. this._visibleInstances[renderId].push(instance);
  27856. return this;
  27857. };
  27858. /**
  27859. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27860. * This means the mesh underlying bounding box and sphere are recomputed.
  27861. * Returns the Mesh.
  27862. */
  27863. Mesh.prototype.refreshBoundingInfo = function () {
  27864. return this._refreshBoundingInfo(false);
  27865. };
  27866. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27867. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27868. return this;
  27869. }
  27870. var data = this._getPositionData(applySkeleton);
  27871. if (data) {
  27872. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27873. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27874. }
  27875. if (this.subMeshes) {
  27876. for (var index = 0; index < this.subMeshes.length; index++) {
  27877. this.subMeshes[index].refreshBoundingInfo();
  27878. }
  27879. }
  27880. this._updateBoundingInfo();
  27881. return this;
  27882. };
  27883. Mesh.prototype._getPositionData = function (applySkeleton) {
  27884. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27885. if (data && applySkeleton && this.skeleton) {
  27886. data = BABYLON.Tools.Slice(data);
  27887. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27888. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27889. if (matricesWeightsData && matricesIndicesData) {
  27890. var needExtras = this.numBoneInfluencers > 4;
  27891. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27892. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27893. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27894. var tempVector = BABYLON.Tmp.Vector3[0];
  27895. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27896. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27897. var matWeightIdx = 0;
  27898. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27899. finalMatrix.reset();
  27900. var inf;
  27901. var weight;
  27902. for (inf = 0; inf < 4; inf++) {
  27903. weight = matricesWeightsData[matWeightIdx + inf];
  27904. if (weight <= 0)
  27905. break;
  27906. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27907. finalMatrix.addToSelf(tempMatrix);
  27908. }
  27909. if (needExtras) {
  27910. for (inf = 0; inf < 4; inf++) {
  27911. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27912. if (weight <= 0)
  27913. break;
  27914. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27915. finalMatrix.addToSelf(tempMatrix);
  27916. }
  27917. }
  27918. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27919. tempVector.toArray(data, index);
  27920. }
  27921. }
  27922. }
  27923. return data;
  27924. };
  27925. Mesh.prototype._createGlobalSubMesh = function (force) {
  27926. var totalVertices = this.getTotalVertices();
  27927. if (!totalVertices || !this.getIndices()) {
  27928. return null;
  27929. }
  27930. // Check if we need to recreate the submeshes
  27931. if (this.subMeshes && this.subMeshes.length > 0) {
  27932. var ib = this.getIndices();
  27933. if (!ib) {
  27934. return null;
  27935. }
  27936. var totalIndices = ib.length;
  27937. var needToRecreate = false;
  27938. if (force) {
  27939. needToRecreate = true;
  27940. }
  27941. else {
  27942. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27943. var submesh = _a[_i];
  27944. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27945. needToRecreate = true;
  27946. break;
  27947. }
  27948. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27949. needToRecreate = true;
  27950. break;
  27951. }
  27952. }
  27953. }
  27954. if (!needToRecreate) {
  27955. return this.subMeshes[0];
  27956. }
  27957. }
  27958. this.releaseSubMeshes();
  27959. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27960. };
  27961. Mesh.prototype.subdivide = function (count) {
  27962. if (count < 1) {
  27963. return;
  27964. }
  27965. var totalIndices = this.getTotalIndices();
  27966. var subdivisionSize = (totalIndices / count) | 0;
  27967. var offset = 0;
  27968. // Ensure that subdivisionSize is a multiple of 3
  27969. while (subdivisionSize % 3 !== 0) {
  27970. subdivisionSize++;
  27971. }
  27972. this.releaseSubMeshes();
  27973. for (var index = 0; index < count; index++) {
  27974. if (offset >= totalIndices) {
  27975. break;
  27976. }
  27977. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27978. offset += subdivisionSize;
  27979. }
  27980. this.synchronizeInstances();
  27981. };
  27982. /**
  27983. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27984. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27985. * The `data` are either a numeric array either a Float32Array.
  27986. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27987. * 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).
  27988. * Note that a new underlying VertexBuffer object is created each call.
  27989. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27990. *
  27991. * Possible `kind` values :
  27992. * - BABYLON.VertexBuffer.PositionKind
  27993. * - BABYLON.VertexBuffer.UVKind
  27994. * - BABYLON.VertexBuffer.UV2Kind
  27995. * - BABYLON.VertexBuffer.UV3Kind
  27996. * - BABYLON.VertexBuffer.UV4Kind
  27997. * - BABYLON.VertexBuffer.UV5Kind
  27998. * - BABYLON.VertexBuffer.UV6Kind
  27999. * - BABYLON.VertexBuffer.ColorKind
  28000. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28001. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28002. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28003. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28004. *
  28005. * Returns the Mesh.
  28006. */
  28007. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28008. if (updatable === void 0) { updatable = false; }
  28009. if (!this._geometry) {
  28010. var vertexData = new BABYLON.VertexData();
  28011. vertexData.set(data, kind);
  28012. var scene = this.getScene();
  28013. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28014. }
  28015. else {
  28016. this._geometry.setVerticesData(kind, data, updatable, stride);
  28017. }
  28018. return this;
  28019. };
  28020. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28021. if (updatable === void 0) { updatable = true; }
  28022. var vb = this.getVertexBuffer(kind);
  28023. if (!vb || vb.isUpdatable() === updatable) {
  28024. return;
  28025. }
  28026. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28027. };
  28028. /**
  28029. * Sets the mesh VertexBuffer.
  28030. * Returns the Mesh.
  28031. */
  28032. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28033. if (!this._geometry) {
  28034. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28035. }
  28036. this._geometry.setVerticesBuffer(buffer);
  28037. return this;
  28038. };
  28039. /**
  28040. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28041. * If the mesh has no geometry, it is simply returned as it is.
  28042. * The `data` are either a numeric array either a Float32Array.
  28043. * No new underlying VertexBuffer object is created.
  28044. * 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.
  28045. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28046. *
  28047. * Possible `kind` values :
  28048. * - BABYLON.VertexBuffer.PositionKind
  28049. * - BABYLON.VertexBuffer.UVKind
  28050. * - BABYLON.VertexBuffer.UV2Kind
  28051. * - BABYLON.VertexBuffer.UV3Kind
  28052. * - BABYLON.VertexBuffer.UV4Kind
  28053. * - BABYLON.VertexBuffer.UV5Kind
  28054. * - BABYLON.VertexBuffer.UV6Kind
  28055. * - BABYLON.VertexBuffer.ColorKind
  28056. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28057. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28058. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28059. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28060. *
  28061. * Returns the Mesh.
  28062. */
  28063. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28064. if (!this._geometry) {
  28065. return this;
  28066. }
  28067. if (!makeItUnique) {
  28068. this._geometry.updateVerticesData(kind, data, updateExtends);
  28069. }
  28070. else {
  28071. this.makeGeometryUnique();
  28072. this.updateVerticesData(kind, data, updateExtends, false);
  28073. }
  28074. return this;
  28075. };
  28076. /**
  28077. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28078. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28079. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28080. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28081. * Returns the Mesh.
  28082. */
  28083. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28084. if (computeNormals === void 0) { computeNormals = true; }
  28085. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28086. if (!positions) {
  28087. return this;
  28088. }
  28089. positionFunction(positions);
  28090. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28091. if (computeNormals) {
  28092. var indices = this.getIndices();
  28093. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28094. if (!normals) {
  28095. return this;
  28096. }
  28097. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28098. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28099. }
  28100. return this;
  28101. };
  28102. /**
  28103. * Creates a un-shared specific occurence of the geometry for the mesh.
  28104. * Returns the Mesh.
  28105. */
  28106. Mesh.prototype.makeGeometryUnique = function () {
  28107. if (!this._geometry) {
  28108. return this;
  28109. }
  28110. var oldGeometry = this._geometry;
  28111. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28112. oldGeometry.releaseForMesh(this, true);
  28113. geometry.applyToMesh(this);
  28114. return this;
  28115. };
  28116. /**
  28117. * Sets the mesh indices.
  28118. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28119. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28120. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28121. * This method creates a new index buffer each call.
  28122. * Returns the Mesh.
  28123. */
  28124. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28125. if (totalVertices === void 0) { totalVertices = null; }
  28126. if (updatable === void 0) { updatable = false; }
  28127. if (!this._geometry) {
  28128. var vertexData = new BABYLON.VertexData();
  28129. vertexData.indices = indices;
  28130. var scene = this.getScene();
  28131. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28132. }
  28133. else {
  28134. this._geometry.setIndices(indices, totalVertices, updatable);
  28135. }
  28136. return this;
  28137. };
  28138. /**
  28139. * Update the current index buffer
  28140. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28141. * Returns the Mesh.
  28142. */
  28143. Mesh.prototype.updateIndices = function (indices, offset) {
  28144. if (!this._geometry) {
  28145. return this;
  28146. }
  28147. this._geometry.updateIndices(indices, offset);
  28148. return this;
  28149. };
  28150. /**
  28151. * Invert the geometry to move from a right handed system to a left handed one.
  28152. * Returns the Mesh.
  28153. */
  28154. Mesh.prototype.toLeftHanded = function () {
  28155. if (!this._geometry) {
  28156. return this;
  28157. }
  28158. this._geometry.toLeftHanded();
  28159. return this;
  28160. };
  28161. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28162. if (!this._geometry) {
  28163. return this;
  28164. }
  28165. var engine = this.getScene().getEngine();
  28166. // Wireframe
  28167. var indexToBind;
  28168. if (this._unIndexed) {
  28169. indexToBind = null;
  28170. }
  28171. else {
  28172. switch (fillMode) {
  28173. case BABYLON.Material.PointFillMode:
  28174. indexToBind = null;
  28175. break;
  28176. case BABYLON.Material.WireFrameFillMode:
  28177. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28178. break;
  28179. default:
  28180. case BABYLON.Material.TriangleFillMode:
  28181. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28182. break;
  28183. }
  28184. }
  28185. // VBOs
  28186. this._geometry._bind(effect, indexToBind);
  28187. return this;
  28188. };
  28189. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28190. if (alternate === void 0) { alternate = false; }
  28191. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28192. return this;
  28193. }
  28194. this.onBeforeDrawObservable.notifyObservers(this);
  28195. var scene = this.getScene();
  28196. var engine = scene.getEngine();
  28197. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28198. // or triangles as points
  28199. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28200. }
  28201. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28202. // Triangles as wireframe
  28203. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28204. }
  28205. else {
  28206. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28207. }
  28208. if (scene._isAlternateRenderingEnabled && !alternate) {
  28209. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28210. if (!effect || !scene.activeCamera) {
  28211. return this;
  28212. }
  28213. scene._switchToAlternateCameraConfiguration(true);
  28214. this._effectiveMaterial.bindView(effect);
  28215. this._effectiveMaterial.bindViewProjection(effect);
  28216. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28217. this._draw(subMesh, fillMode, instancesCount, true);
  28218. engine.setViewport(scene.activeCamera.viewport);
  28219. scene._switchToAlternateCameraConfiguration(false);
  28220. this._effectiveMaterial.bindView(effect);
  28221. this._effectiveMaterial.bindViewProjection(effect);
  28222. }
  28223. return this;
  28224. };
  28225. /**
  28226. * Registers for this mesh a javascript function called just before the rendering process.
  28227. * This function is passed the current mesh.
  28228. * Return the Mesh.
  28229. */
  28230. Mesh.prototype.registerBeforeRender = function (func) {
  28231. this.onBeforeRenderObservable.add(func);
  28232. return this;
  28233. };
  28234. /**
  28235. * Disposes a previously registered javascript function called before the rendering.
  28236. * This function is passed the current mesh.
  28237. * Returns the Mesh.
  28238. */
  28239. Mesh.prototype.unregisterBeforeRender = function (func) {
  28240. this.onBeforeRenderObservable.removeCallback(func);
  28241. return this;
  28242. };
  28243. /**
  28244. * Registers for this mesh a javascript function called just after the rendering is complete.
  28245. * This function is passed the current mesh.
  28246. * Returns the Mesh.
  28247. */
  28248. Mesh.prototype.registerAfterRender = function (func) {
  28249. this.onAfterRenderObservable.add(func);
  28250. return this;
  28251. };
  28252. /**
  28253. * Disposes a previously registered javascript function called after the rendering.
  28254. * This function is passed the current mesh.
  28255. * Return the Mesh.
  28256. */
  28257. Mesh.prototype.unregisterAfterRender = function (func) {
  28258. this.onAfterRenderObservable.removeCallback(func);
  28259. return this;
  28260. };
  28261. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28262. var scene = this.getScene();
  28263. this._batchCache.mustReturn = false;
  28264. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28265. this._batchCache.visibleInstances[subMeshId] = null;
  28266. if (this._visibleInstances) {
  28267. var currentRenderId = scene.getRenderId();
  28268. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28269. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28270. var selfRenderId = this._renderId;
  28271. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28272. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28273. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28274. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28275. }
  28276. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28277. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28278. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28279. this._batchCache.mustReturn = true;
  28280. return this._batchCache;
  28281. }
  28282. if (currentRenderId !== selfRenderId) {
  28283. this._batchCache.renderSelf[subMeshId] = false;
  28284. }
  28285. }
  28286. this._renderIdForInstances[subMeshId] = currentRenderId;
  28287. }
  28288. return this._batchCache;
  28289. };
  28290. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28291. var visibleInstances = batch.visibleInstances[subMesh._id];
  28292. if (!visibleInstances) {
  28293. return this;
  28294. }
  28295. var matricesCount = visibleInstances.length + 1;
  28296. var bufferSize = matricesCount * 16 * 4;
  28297. var currentInstancesBufferSize = this._instancesBufferSize;
  28298. var instancesBuffer = this._instancesBuffer;
  28299. while (this._instancesBufferSize < bufferSize) {
  28300. this._instancesBufferSize *= 2;
  28301. }
  28302. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28303. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28304. }
  28305. var offset = 0;
  28306. var instancesCount = 0;
  28307. var world = this.getWorldMatrix();
  28308. if (batch.renderSelf[subMesh._id]) {
  28309. world.copyToArray(this._instancesData, offset);
  28310. offset += 16;
  28311. instancesCount++;
  28312. }
  28313. if (visibleInstances) {
  28314. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28315. var instance = visibleInstances[instanceIndex];
  28316. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28317. offset += 16;
  28318. instancesCount++;
  28319. }
  28320. }
  28321. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28322. if (instancesBuffer) {
  28323. instancesBuffer.dispose();
  28324. }
  28325. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28326. this._instancesBuffer = instancesBuffer;
  28327. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28328. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28329. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28330. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28331. }
  28332. else {
  28333. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28334. }
  28335. this._bind(subMesh, effect, fillMode);
  28336. this._draw(subMesh, fillMode, instancesCount);
  28337. engine.unbindInstanceAttributes();
  28338. return this;
  28339. };
  28340. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28341. var scene = this.getScene();
  28342. var engine = scene.getEngine();
  28343. if (hardwareInstancedRendering) {
  28344. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28345. }
  28346. else {
  28347. if (batch.renderSelf[subMesh._id]) {
  28348. // Draw
  28349. if (onBeforeDraw) {
  28350. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28351. }
  28352. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28353. }
  28354. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28355. if (visibleInstancesForSubMesh) {
  28356. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28357. var instance = visibleInstancesForSubMesh[instanceIndex];
  28358. // World
  28359. var world = instance.getWorldMatrix();
  28360. if (onBeforeDraw) {
  28361. onBeforeDraw(true, world, effectiveMaterial);
  28362. }
  28363. // Draw
  28364. this._draw(subMesh, fillMode);
  28365. }
  28366. }
  28367. }
  28368. return this;
  28369. };
  28370. /**
  28371. * Triggers the draw call for the mesh.
  28372. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28373. * Returns the Mesh.
  28374. */
  28375. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28376. this.checkOcclusionQuery();
  28377. if (this._isOccluded) {
  28378. return this;
  28379. }
  28380. var scene = this.getScene();
  28381. // Managing instances
  28382. var batch = this._getInstancesRenderList(subMesh._id);
  28383. if (batch.mustReturn) {
  28384. return this;
  28385. }
  28386. // Checking geometry state
  28387. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28388. return this;
  28389. }
  28390. this.onBeforeRenderObservable.notifyObservers(this);
  28391. var engine = scene.getEngine();
  28392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28393. // Material
  28394. var material = subMesh.getMaterial();
  28395. if (!material) {
  28396. return this;
  28397. }
  28398. this._effectiveMaterial = material;
  28399. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28400. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28401. return this;
  28402. }
  28403. }
  28404. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28405. return this;
  28406. }
  28407. // Alpha mode
  28408. if (enableAlphaMode) {
  28409. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28410. }
  28411. // Outline - step 1
  28412. var savedDepthWrite = engine.getDepthWrite();
  28413. if (this.renderOutline) {
  28414. engine.setDepthWrite(false);
  28415. scene.getOutlineRenderer().render(subMesh, batch);
  28416. engine.setDepthWrite(savedDepthWrite);
  28417. }
  28418. var effect;
  28419. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28420. effect = subMesh.effect;
  28421. }
  28422. else {
  28423. effect = this._effectiveMaterial.getEffect();
  28424. }
  28425. if (!effect) {
  28426. return this;
  28427. }
  28428. var sideOrientation = this.overrideMaterialSideOrientation;
  28429. if (sideOrientation == null) {
  28430. sideOrientation = this._effectiveMaterial.sideOrientation;
  28431. if (this._getWorldMatrixDeterminant() < 0) {
  28432. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28433. }
  28434. }
  28435. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28436. if (this._effectiveMaterial.forceDepthWrite) {
  28437. engine.setDepthWrite(true);
  28438. }
  28439. // Bind
  28440. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28441. if (!hardwareInstancedRendering) {
  28442. this._bind(subMesh, effect, fillMode);
  28443. }
  28444. var world = this.getWorldMatrix();
  28445. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28446. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28447. }
  28448. else {
  28449. this._effectiveMaterial.bind(world, this);
  28450. }
  28451. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28452. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28453. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28454. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28455. }
  28456. // Draw
  28457. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28458. // Unbind
  28459. this._effectiveMaterial.unbind();
  28460. // Outline - step 2
  28461. if (this.renderOutline && savedDepthWrite) {
  28462. engine.setDepthWrite(true);
  28463. engine.setColorWrite(false);
  28464. scene.getOutlineRenderer().render(subMesh, batch);
  28465. engine.setColorWrite(true);
  28466. }
  28467. // Overlay
  28468. if (this.renderOverlay) {
  28469. var currentMode = engine.getAlphaMode();
  28470. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28471. scene.getOutlineRenderer().render(subMesh, batch, true);
  28472. engine.setAlphaMode(currentMode);
  28473. }
  28474. this.onAfterRenderObservable.notifyObservers(this);
  28475. return this;
  28476. };
  28477. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28478. if (isInstance && effectiveMaterial) {
  28479. effectiveMaterial.bindOnlyWorldMatrix(world);
  28480. }
  28481. };
  28482. /**
  28483. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28484. */
  28485. Mesh.prototype.getEmittedParticleSystems = function () {
  28486. var results = new Array();
  28487. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28488. var particleSystem = this.getScene().particleSystems[index];
  28489. if (particleSystem.emitter === this) {
  28490. results.push(particleSystem);
  28491. }
  28492. }
  28493. return results;
  28494. };
  28495. /**
  28496. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28497. */
  28498. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28499. var results = new Array();
  28500. var descendants = this.getDescendants();
  28501. descendants.push(this);
  28502. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28503. var particleSystem = this.getScene().particleSystems[index];
  28504. var emitter = particleSystem.emitter;
  28505. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28506. results.push(particleSystem);
  28507. }
  28508. }
  28509. return results;
  28510. };
  28511. Mesh.prototype._checkDelayState = function () {
  28512. var scene = this.getScene();
  28513. if (this._geometry) {
  28514. this._geometry.load(scene);
  28515. }
  28516. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28517. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28518. this._queueLoad(scene);
  28519. }
  28520. return this;
  28521. };
  28522. Mesh.prototype._queueLoad = function (scene) {
  28523. var _this = this;
  28524. scene._addPendingData(this);
  28525. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28526. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28527. if (data instanceof ArrayBuffer) {
  28528. _this._delayLoadingFunction(data, _this);
  28529. }
  28530. else {
  28531. _this._delayLoadingFunction(JSON.parse(data), _this);
  28532. }
  28533. _this.instances.forEach(function (instance) {
  28534. instance._syncSubMeshes();
  28535. });
  28536. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28537. scene._removePendingData(_this);
  28538. }, function () { }, scene.database, getBinaryData);
  28539. return this;
  28540. };
  28541. /**
  28542. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28543. */
  28544. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28545. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28546. return false;
  28547. }
  28548. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28549. return false;
  28550. }
  28551. this._checkDelayState();
  28552. return true;
  28553. };
  28554. /**
  28555. * Sets the mesh material by the material or multiMaterial `id` property.
  28556. * The material `id` is a string identifying the material or the multiMaterial.
  28557. * This method returns the Mesh.
  28558. */
  28559. Mesh.prototype.setMaterialByID = function (id) {
  28560. var materials = this.getScene().materials;
  28561. var index;
  28562. for (index = materials.length - 1; index > -1; index--) {
  28563. if (materials[index].id === id) {
  28564. this.material = materials[index];
  28565. return this;
  28566. }
  28567. }
  28568. // Multi
  28569. var multiMaterials = this.getScene().multiMaterials;
  28570. for (index = multiMaterials.length - 1; index > -1; index--) {
  28571. if (multiMaterials[index].id === id) {
  28572. this.material = multiMaterials[index];
  28573. return this;
  28574. }
  28575. }
  28576. return this;
  28577. };
  28578. /**
  28579. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28580. */
  28581. Mesh.prototype.getAnimatables = function () {
  28582. var results = new Array();
  28583. if (this.material) {
  28584. results.push(this.material);
  28585. }
  28586. if (this.skeleton) {
  28587. results.push(this.skeleton);
  28588. }
  28589. return results;
  28590. };
  28591. /**
  28592. * Modifies the mesh geometry according to the passed transformation matrix.
  28593. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28594. * The mesh normals are modified accordingly the same transformation.
  28595. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28596. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28597. * Returns the Mesh.
  28598. */
  28599. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28600. // Position
  28601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28602. return this;
  28603. }
  28604. var submeshes = this.subMeshes.splice(0);
  28605. this._resetPointsArrayCache();
  28606. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28607. var temp = new Array();
  28608. var index;
  28609. for (index = 0; index < data.length; index += 3) {
  28610. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28611. }
  28612. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28613. // Normals
  28614. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28615. return this;
  28616. }
  28617. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28618. temp = [];
  28619. for (index = 0; index < data.length; index += 3) {
  28620. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28621. }
  28622. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28623. // flip faces?
  28624. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28625. this.flipFaces();
  28626. }
  28627. // Restore submeshes
  28628. this.releaseSubMeshes();
  28629. this.subMeshes = submeshes;
  28630. return this;
  28631. };
  28632. /**
  28633. * Modifies the mesh geometry according to its own current World Matrix.
  28634. * The mesh World Matrix is then reset.
  28635. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28636. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28637. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28638. * Returns the Mesh.
  28639. */
  28640. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28641. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28642. this.scaling.copyFromFloats(1, 1, 1);
  28643. this.position.copyFromFloats(0, 0, 0);
  28644. this.rotation.copyFromFloats(0, 0, 0);
  28645. //only if quaternion is already set
  28646. if (this.rotationQuaternion) {
  28647. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28648. }
  28649. this._worldMatrix = BABYLON.Matrix.Identity();
  28650. return this;
  28651. };
  28652. Object.defineProperty(Mesh.prototype, "_positions", {
  28653. // Cache
  28654. get: function () {
  28655. if (this._geometry) {
  28656. return this._geometry._positions;
  28657. }
  28658. return null;
  28659. },
  28660. enumerable: true,
  28661. configurable: true
  28662. });
  28663. Mesh.prototype._resetPointsArrayCache = function () {
  28664. if (this._geometry) {
  28665. this._geometry._resetPointsArrayCache();
  28666. }
  28667. return this;
  28668. };
  28669. Mesh.prototype._generatePointsArray = function () {
  28670. if (this._geometry) {
  28671. return this._geometry._generatePointsArray();
  28672. }
  28673. return false;
  28674. };
  28675. /**
  28676. * Returns a new Mesh object generated from the current mesh properties.
  28677. * This method must not get confused with createInstance().
  28678. * The parameter `name` is a string, the name given to the new mesh.
  28679. * The optional parameter `newParent` can be any Node object (default `null`).
  28680. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28681. * 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.
  28682. */
  28683. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28684. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28685. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28686. };
  28687. /**
  28688. * Disposes the Mesh.
  28689. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28690. * Returns nothing.
  28691. */
  28692. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28693. var _this = this;
  28694. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28695. this.morphTargetManager = null;
  28696. if (this._geometry) {
  28697. this._geometry.releaseForMesh(this, true);
  28698. }
  28699. // Sources
  28700. var meshes = this.getScene().meshes;
  28701. meshes.forEach(function (abstractMesh) {
  28702. var mesh = abstractMesh;
  28703. if (mesh._source && mesh._source === _this) {
  28704. mesh._source = null;
  28705. }
  28706. });
  28707. this._source = null;
  28708. // Instances
  28709. if (this._instancesBuffer) {
  28710. this._instancesBuffer.dispose();
  28711. this._instancesBuffer = null;
  28712. }
  28713. while (this.instances.length) {
  28714. this.instances[0].dispose();
  28715. }
  28716. // Effect layers.
  28717. var effectLayers = this.getScene().effectLayers;
  28718. for (var i = 0; i < effectLayers.length; i++) {
  28719. var effectLayer = effectLayers[i];
  28720. if (effectLayer) {
  28721. effectLayer._disposeMesh(this);
  28722. }
  28723. }
  28724. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28725. };
  28726. /**
  28727. * Modifies the mesh geometry according to a displacement map.
  28728. * 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.
  28729. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28730. * This method returns nothing.
  28731. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28732. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28733. * 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.
  28734. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28735. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28736. *
  28737. * Returns the Mesh.
  28738. */
  28739. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28740. var _this = this;
  28741. var scene = this.getScene();
  28742. var onload = function (img) {
  28743. // Getting height map data
  28744. var canvas = document.createElement("canvas");
  28745. var context = canvas.getContext("2d");
  28746. var heightMapWidth = img.width;
  28747. var heightMapHeight = img.height;
  28748. canvas.width = heightMapWidth;
  28749. canvas.height = heightMapHeight;
  28750. context.drawImage(img, 0, 0);
  28751. // Create VertexData from map data
  28752. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28753. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28754. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28755. //execute success callback, if set
  28756. if (onSuccess) {
  28757. onSuccess(_this);
  28758. }
  28759. };
  28760. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28761. return this;
  28762. };
  28763. /**
  28764. * Modifies the mesh geometry according to a displacementMap buffer.
  28765. * 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.
  28766. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28767. * This method returns nothing.
  28768. * 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.
  28769. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28770. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28771. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28772. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28773. *
  28774. * Returns the Mesh.
  28775. */
  28776. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28777. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28778. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28779. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28780. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28781. return this;
  28782. }
  28783. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28784. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28785. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28786. var position = BABYLON.Vector3.Zero();
  28787. var normal = BABYLON.Vector3.Zero();
  28788. var uv = BABYLON.Vector2.Zero();
  28789. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28790. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28791. for (var index = 0; index < positions.length; index += 3) {
  28792. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28793. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28794. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28795. // Compute height
  28796. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28797. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28798. var pos = (u + v * heightMapWidth) * 4;
  28799. var r = buffer[pos] / 255.0;
  28800. var g = buffer[pos + 1] / 255.0;
  28801. var b = buffer[pos + 2] / 255.0;
  28802. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28803. normal.normalize();
  28804. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28805. position = position.add(normal);
  28806. position.toArray(positions, index);
  28807. }
  28808. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28809. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28810. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28811. return this;
  28812. };
  28813. /**
  28814. * Modify the mesh to get a flat shading rendering.
  28815. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28816. * This method returns the Mesh.
  28817. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28818. */
  28819. Mesh.prototype.convertToFlatShadedMesh = function () {
  28820. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28821. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28822. var kinds = this.getVerticesDataKinds();
  28823. var vbs = {};
  28824. var data = {};
  28825. var newdata = {};
  28826. var updatableNormals = false;
  28827. var kindIndex;
  28828. var kind;
  28829. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28830. kind = kinds[kindIndex];
  28831. var vertexBuffer = this.getVertexBuffer(kind);
  28832. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28833. updatableNormals = vertexBuffer.isUpdatable();
  28834. kinds.splice(kindIndex, 1);
  28835. kindIndex--;
  28836. continue;
  28837. }
  28838. vbs[kind] = vertexBuffer;
  28839. data[kind] = vbs[kind].getData();
  28840. newdata[kind] = [];
  28841. }
  28842. // Save previous submeshes
  28843. var previousSubmeshes = this.subMeshes.slice(0);
  28844. var indices = this.getIndices();
  28845. var totalIndices = this.getTotalIndices();
  28846. // Generating unique vertices per face
  28847. var index;
  28848. for (index = 0; index < totalIndices; index++) {
  28849. var vertexIndex = indices[index];
  28850. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28851. kind = kinds[kindIndex];
  28852. var stride = vbs[kind].getStrideSize();
  28853. for (var offset = 0; offset < stride; offset++) {
  28854. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28855. }
  28856. }
  28857. }
  28858. // Updating faces & normal
  28859. var normals = [];
  28860. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28861. for (index = 0; index < totalIndices; index += 3) {
  28862. indices[index] = index;
  28863. indices[index + 1] = index + 1;
  28864. indices[index + 2] = index + 2;
  28865. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28866. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28867. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28868. var p1p2 = p1.subtract(p2);
  28869. var p3p2 = p3.subtract(p2);
  28870. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28871. // Store same normals for every vertex
  28872. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28873. normals.push(normal.x);
  28874. normals.push(normal.y);
  28875. normals.push(normal.z);
  28876. }
  28877. }
  28878. this.setIndices(indices);
  28879. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28880. // Updating vertex buffers
  28881. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28882. kind = kinds[kindIndex];
  28883. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28884. }
  28885. // Updating submeshes
  28886. this.releaseSubMeshes();
  28887. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28888. var previousOne = previousSubmeshes[submeshIndex];
  28889. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28890. }
  28891. this.synchronizeInstances();
  28892. return this;
  28893. };
  28894. /**
  28895. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28896. * In other words, more vertices, no more indices and a single bigger VBO.
  28897. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28898. * Returns the Mesh.
  28899. */
  28900. Mesh.prototype.convertToUnIndexedMesh = function () {
  28901. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28902. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28903. var kinds = this.getVerticesDataKinds();
  28904. var vbs = {};
  28905. var data = {};
  28906. var newdata = {};
  28907. var kindIndex;
  28908. var kind;
  28909. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28910. kind = kinds[kindIndex];
  28911. var vertexBuffer = this.getVertexBuffer(kind);
  28912. vbs[kind] = vertexBuffer;
  28913. data[kind] = vbs[kind].getData();
  28914. newdata[kind] = [];
  28915. }
  28916. // Save previous submeshes
  28917. var previousSubmeshes = this.subMeshes.slice(0);
  28918. var indices = this.getIndices();
  28919. var totalIndices = this.getTotalIndices();
  28920. // Generating unique vertices per face
  28921. var index;
  28922. for (index = 0; index < totalIndices; index++) {
  28923. var vertexIndex = indices[index];
  28924. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28925. kind = kinds[kindIndex];
  28926. var stride = vbs[kind].getStrideSize();
  28927. for (var offset = 0; offset < stride; offset++) {
  28928. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28929. }
  28930. }
  28931. }
  28932. // Updating indices
  28933. for (index = 0; index < totalIndices; index += 3) {
  28934. indices[index] = index;
  28935. indices[index + 1] = index + 1;
  28936. indices[index + 2] = index + 2;
  28937. }
  28938. this.setIndices(indices);
  28939. // Updating vertex buffers
  28940. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28941. kind = kinds[kindIndex];
  28942. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28943. }
  28944. // Updating submeshes
  28945. this.releaseSubMeshes();
  28946. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28947. var previousOne = previousSubmeshes[submeshIndex];
  28948. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28949. }
  28950. this._unIndexed = true;
  28951. this.synchronizeInstances();
  28952. return this;
  28953. };
  28954. /**
  28955. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28956. * This method returns the Mesh.
  28957. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28958. */
  28959. Mesh.prototype.flipFaces = function (flipNormals) {
  28960. if (flipNormals === void 0) { flipNormals = false; }
  28961. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28962. var i;
  28963. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28964. for (i = 0; i < vertex_data.normals.length; i++) {
  28965. vertex_data.normals[i] *= -1;
  28966. }
  28967. }
  28968. if (vertex_data.indices) {
  28969. var temp;
  28970. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28971. // reassign indices
  28972. temp = vertex_data.indices[i + 1];
  28973. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28974. vertex_data.indices[i + 2] = temp;
  28975. }
  28976. }
  28977. vertex_data.applyToMesh(this);
  28978. return this;
  28979. };
  28980. // Instances
  28981. /**
  28982. * Creates a new InstancedMesh object from the mesh model.
  28983. * An instance shares the same properties and the same material than its model.
  28984. * Only these properties of each instance can then be set individually :
  28985. * - position
  28986. * - rotation
  28987. * - rotationQuaternion
  28988. * - setPivotMatrix
  28989. * - scaling
  28990. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28991. * Warning : this method is not supported for Line mesh and LineSystem
  28992. */
  28993. Mesh.prototype.createInstance = function (name) {
  28994. return new BABYLON.InstancedMesh(name, this);
  28995. };
  28996. /**
  28997. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28998. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28999. * This method returns the Mesh.
  29000. */
  29001. Mesh.prototype.synchronizeInstances = function () {
  29002. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29003. var instance = this.instances[instanceIndex];
  29004. instance._syncSubMeshes();
  29005. }
  29006. return this;
  29007. };
  29008. /**
  29009. * Simplify the mesh according to the given array of settings.
  29010. * Function will return immediately and will simplify async. It returns the Mesh.
  29011. * @param settings a collection of simplification settings.
  29012. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29013. * @param type the type of simplification to run.
  29014. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29015. */
  29016. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29017. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29018. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29019. this.getScene().simplificationQueue.addTask({
  29020. settings: settings,
  29021. parallelProcessing: parallelProcessing,
  29022. mesh: this,
  29023. simplificationType: simplificationType,
  29024. successCallback: successCallback
  29025. });
  29026. return this;
  29027. };
  29028. /**
  29029. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29030. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29031. * This should be used together with the simplification to avoid disappearing triangles.
  29032. * Returns the Mesh.
  29033. * @param successCallback an optional success callback to be called after the optimization finished.
  29034. */
  29035. Mesh.prototype.optimizeIndices = function (successCallback) {
  29036. var _this = this;
  29037. var indices = this.getIndices();
  29038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29039. if (!positions || !indices) {
  29040. return this;
  29041. }
  29042. var vectorPositions = new Array();
  29043. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29044. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29045. }
  29046. var dupes = new Array();
  29047. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29048. var realPos = vectorPositions.length - 1 - iteration;
  29049. var testedPosition = vectorPositions[realPos];
  29050. for (var j = 0; j < realPos; ++j) {
  29051. var againstPosition = vectorPositions[j];
  29052. if (testedPosition.equals(againstPosition)) {
  29053. dupes[realPos] = j;
  29054. break;
  29055. }
  29056. }
  29057. }, function () {
  29058. for (var i = 0; i < indices.length; ++i) {
  29059. indices[i] = dupes[indices[i]] || indices[i];
  29060. }
  29061. //indices are now reordered
  29062. var originalSubMeshes = _this.subMeshes.slice(0);
  29063. _this.setIndices(indices);
  29064. _this.subMeshes = originalSubMeshes;
  29065. if (successCallback) {
  29066. successCallback(_this);
  29067. }
  29068. });
  29069. return this;
  29070. };
  29071. Mesh.prototype.serialize = function (serializationObject) {
  29072. serializationObject.name = this.name;
  29073. serializationObject.id = this.id;
  29074. serializationObject.type = this.getClassName();
  29075. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29076. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29077. }
  29078. serializationObject.position = this.position.asArray();
  29079. if (this.rotationQuaternion) {
  29080. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29081. }
  29082. else if (this.rotation) {
  29083. serializationObject.rotation = this.rotation.asArray();
  29084. }
  29085. serializationObject.scaling = this.scaling.asArray();
  29086. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29087. serializationObject.isEnabled = this.isEnabled(false);
  29088. serializationObject.isVisible = this.isVisible;
  29089. serializationObject.infiniteDistance = this.infiniteDistance;
  29090. serializationObject.pickable = this.isPickable;
  29091. serializationObject.receiveShadows = this.receiveShadows;
  29092. serializationObject.billboardMode = this.billboardMode;
  29093. serializationObject.visibility = this.visibility;
  29094. serializationObject.checkCollisions = this.checkCollisions;
  29095. serializationObject.isBlocker = this.isBlocker;
  29096. // Parent
  29097. if (this.parent) {
  29098. serializationObject.parentId = this.parent.id;
  29099. }
  29100. // Geometry
  29101. serializationObject.isUnIndexed = this.isUnIndexed;
  29102. var geometry = this._geometry;
  29103. if (geometry) {
  29104. var geometryId = geometry.id;
  29105. serializationObject.geometryId = geometryId;
  29106. // SubMeshes
  29107. serializationObject.subMeshes = [];
  29108. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29109. var subMesh = this.subMeshes[subIndex];
  29110. serializationObject.subMeshes.push({
  29111. materialIndex: subMesh.materialIndex,
  29112. verticesStart: subMesh.verticesStart,
  29113. verticesCount: subMesh.verticesCount,
  29114. indexStart: subMesh.indexStart,
  29115. indexCount: subMesh.indexCount
  29116. });
  29117. }
  29118. }
  29119. // Material
  29120. if (this.material) {
  29121. serializationObject.materialId = this.material.id;
  29122. }
  29123. else {
  29124. this.material = null;
  29125. }
  29126. // Morph targets
  29127. if (this.morphTargetManager) {
  29128. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29129. }
  29130. // Skeleton
  29131. if (this.skeleton) {
  29132. serializationObject.skeletonId = this.skeleton.id;
  29133. }
  29134. // Physics
  29135. //TODO implement correct serialization for physics impostors.
  29136. var impostor = this.getPhysicsImpostor();
  29137. if (impostor) {
  29138. serializationObject.physicsMass = impostor.getParam("mass");
  29139. serializationObject.physicsFriction = impostor.getParam("friction");
  29140. serializationObject.physicsRestitution = impostor.getParam("mass");
  29141. serializationObject.physicsImpostor = impostor.type;
  29142. }
  29143. // Metadata
  29144. if (this.metadata) {
  29145. serializationObject.metadata = this.metadata;
  29146. }
  29147. // Instances
  29148. serializationObject.instances = [];
  29149. for (var index = 0; index < this.instances.length; index++) {
  29150. var instance = this.instances[index];
  29151. var serializationInstance = {
  29152. name: instance.name,
  29153. id: instance.id,
  29154. position: instance.position.asArray(),
  29155. scaling: instance.scaling.asArray()
  29156. };
  29157. if (instance.rotationQuaternion) {
  29158. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29159. }
  29160. else if (instance.rotation) {
  29161. serializationInstance.rotation = instance.rotation.asArray();
  29162. }
  29163. serializationObject.instances.push(serializationInstance);
  29164. // Animations
  29165. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29166. serializationInstance.ranges = instance.serializeAnimationRanges();
  29167. }
  29168. //
  29169. // Animations
  29170. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29171. serializationObject.ranges = this.serializeAnimationRanges();
  29172. // Layer mask
  29173. serializationObject.layerMask = this.layerMask;
  29174. // Alpha
  29175. serializationObject.alphaIndex = this.alphaIndex;
  29176. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29177. // Overlay
  29178. serializationObject.overlayAlpha = this.overlayAlpha;
  29179. serializationObject.overlayColor = this.overlayColor.asArray();
  29180. serializationObject.renderOverlay = this.renderOverlay;
  29181. // Fog
  29182. serializationObject.applyFog = this.applyFog;
  29183. // Action Manager
  29184. if (this.actionManager) {
  29185. serializationObject.actions = this.actionManager.serialize(this.name);
  29186. }
  29187. };
  29188. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29189. if (!this.geometry) {
  29190. return;
  29191. }
  29192. this._markSubMeshesAsAttributesDirty();
  29193. var morphTargetManager = this._morphTargetManager;
  29194. if (morphTargetManager && morphTargetManager.vertexCount) {
  29195. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29196. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29197. this.morphTargetManager = null;
  29198. return;
  29199. }
  29200. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29201. var morphTarget = morphTargetManager.getActiveTarget(index);
  29202. var positions = morphTarget.getPositions();
  29203. if (!positions) {
  29204. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29205. return;
  29206. }
  29207. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29208. var normals = morphTarget.getNormals();
  29209. if (normals) {
  29210. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29211. }
  29212. var tangents = morphTarget.getTangents();
  29213. if (tangents) {
  29214. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29215. }
  29216. }
  29217. }
  29218. else {
  29219. var index = 0;
  29220. // Positions
  29221. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29222. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29223. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29224. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29225. }
  29226. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29227. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29228. }
  29229. index++;
  29230. }
  29231. }
  29232. };
  29233. // Statics
  29234. /**
  29235. * Returns a new Mesh object parsed from the source provided.
  29236. * The parameter `parsedMesh` is the source.
  29237. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29238. */
  29239. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29240. var mesh;
  29241. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29242. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29243. }
  29244. else {
  29245. mesh = new Mesh(parsedMesh.name, scene);
  29246. }
  29247. mesh.id = parsedMesh.id;
  29248. if (BABYLON.Tags) {
  29249. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29250. }
  29251. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29252. if (parsedMesh.metadata !== undefined) {
  29253. mesh.metadata = parsedMesh.metadata;
  29254. }
  29255. if (parsedMesh.rotationQuaternion) {
  29256. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29257. }
  29258. else if (parsedMesh.rotation) {
  29259. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29260. }
  29261. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29262. if (parsedMesh.localMatrix) {
  29263. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29264. }
  29265. else if (parsedMesh.pivotMatrix) {
  29266. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29267. }
  29268. mesh.setEnabled(parsedMesh.isEnabled);
  29269. mesh.isVisible = parsedMesh.isVisible;
  29270. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29271. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29272. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29273. if (parsedMesh.applyFog !== undefined) {
  29274. mesh.applyFog = parsedMesh.applyFog;
  29275. }
  29276. if (parsedMesh.pickable !== undefined) {
  29277. mesh.isPickable = parsedMesh.pickable;
  29278. }
  29279. if (parsedMesh.alphaIndex !== undefined) {
  29280. mesh.alphaIndex = parsedMesh.alphaIndex;
  29281. }
  29282. mesh.receiveShadows = parsedMesh.receiveShadows;
  29283. mesh.billboardMode = parsedMesh.billboardMode;
  29284. if (parsedMesh.visibility !== undefined) {
  29285. mesh.visibility = parsedMesh.visibility;
  29286. }
  29287. mesh.checkCollisions = parsedMesh.checkCollisions;
  29288. if (parsedMesh.isBlocker !== undefined) {
  29289. mesh.isBlocker = parsedMesh.isBlocker;
  29290. }
  29291. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29292. // freezeWorldMatrix
  29293. if (parsedMesh.freezeWorldMatrix) {
  29294. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29295. }
  29296. // Parent
  29297. if (parsedMesh.parentId) {
  29298. mesh._waitingParentId = parsedMesh.parentId;
  29299. }
  29300. // Actions
  29301. if (parsedMesh.actions !== undefined) {
  29302. mesh._waitingActions = parsedMesh.actions;
  29303. }
  29304. // Overlay
  29305. if (parsedMesh.overlayAlpha !== undefined) {
  29306. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29307. }
  29308. if (parsedMesh.overlayColor !== undefined) {
  29309. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29310. }
  29311. if (parsedMesh.renderOverlay !== undefined) {
  29312. mesh.renderOverlay = parsedMesh.renderOverlay;
  29313. }
  29314. // Geometry
  29315. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29316. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29317. if (parsedMesh.delayLoadingFile) {
  29318. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29319. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29320. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29321. if (parsedMesh._binaryInfo) {
  29322. mesh._binaryInfo = parsedMesh._binaryInfo;
  29323. }
  29324. mesh._delayInfo = [];
  29325. if (parsedMesh.hasUVs) {
  29326. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29327. }
  29328. if (parsedMesh.hasUVs2) {
  29329. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29330. }
  29331. if (parsedMesh.hasUVs3) {
  29332. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29333. }
  29334. if (parsedMesh.hasUVs4) {
  29335. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29336. }
  29337. if (parsedMesh.hasUVs5) {
  29338. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29339. }
  29340. if (parsedMesh.hasUVs6) {
  29341. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29342. }
  29343. if (parsedMesh.hasColors) {
  29344. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29345. }
  29346. if (parsedMesh.hasMatricesIndices) {
  29347. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29348. }
  29349. if (parsedMesh.hasMatricesWeights) {
  29350. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29351. }
  29352. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29353. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29354. mesh._checkDelayState();
  29355. }
  29356. }
  29357. else {
  29358. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29359. }
  29360. // Material
  29361. if (parsedMesh.materialId) {
  29362. mesh.setMaterialByID(parsedMesh.materialId);
  29363. }
  29364. else {
  29365. mesh.material = null;
  29366. }
  29367. // Morph targets
  29368. if (parsedMesh.morphTargetManagerId > -1) {
  29369. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29370. }
  29371. // Skeleton
  29372. if (parsedMesh.skeletonId > -1) {
  29373. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29374. if (parsedMesh.numBoneInfluencers) {
  29375. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29376. }
  29377. }
  29378. // Animations
  29379. if (parsedMesh.animations) {
  29380. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29381. var parsedAnimation = parsedMesh.animations[animationIndex];
  29382. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29383. }
  29384. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29385. }
  29386. if (parsedMesh.autoAnimate) {
  29387. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29388. }
  29389. // Layer Mask
  29390. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29391. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29392. }
  29393. else {
  29394. mesh.layerMask = 0x0FFFFFFF;
  29395. }
  29396. // Physics
  29397. if (parsedMesh.physicsImpostor) {
  29398. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29399. mass: parsedMesh.physicsMass,
  29400. friction: parsedMesh.physicsFriction,
  29401. restitution: parsedMesh.physicsRestitution
  29402. }, scene);
  29403. }
  29404. // Instances
  29405. if (parsedMesh.instances) {
  29406. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29407. var parsedInstance = parsedMesh.instances[index];
  29408. var instance = mesh.createInstance(parsedInstance.name);
  29409. if (parsedInstance.id) {
  29410. instance.id = parsedInstance.id;
  29411. }
  29412. if (BABYLON.Tags) {
  29413. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29414. }
  29415. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29416. if (parsedInstance.parentId) {
  29417. instance._waitingParentId = parsedInstance.parentId;
  29418. }
  29419. if (parsedInstance.rotationQuaternion) {
  29420. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29421. }
  29422. else if (parsedInstance.rotation) {
  29423. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29424. }
  29425. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29426. instance.checkCollisions = mesh.checkCollisions;
  29427. if (parsedMesh.animations) {
  29428. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29429. parsedAnimation = parsedMesh.animations[animationIndex];
  29430. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29431. }
  29432. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29433. }
  29434. }
  29435. }
  29436. return mesh;
  29437. };
  29438. /**
  29439. * Creates a ribbon mesh.
  29440. * Please consider using the same method from the MeshBuilder class instead.
  29441. * 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.
  29442. *
  29443. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29444. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29445. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29446. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29447. * 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.
  29448. * 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.
  29449. * 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
  29450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29453. */
  29454. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29455. if (closeArray === void 0) { closeArray = false; }
  29456. if (updatable === void 0) { updatable = false; }
  29457. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29458. pathArray: pathArray,
  29459. closeArray: closeArray,
  29460. closePath: closePath,
  29461. offset: offset,
  29462. updatable: updatable,
  29463. sideOrientation: sideOrientation,
  29464. instance: instance
  29465. }, scene);
  29466. };
  29467. /**
  29468. * Creates a plane polygonal mesh. By default, this is a disc.
  29469. * Please consider using the same method from the MeshBuilder class instead.
  29470. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29471. * 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.
  29472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29473. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29475. */
  29476. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29477. if (scene === void 0) { scene = null; }
  29478. var options = {
  29479. radius: radius,
  29480. tessellation: tessellation,
  29481. sideOrientation: sideOrientation,
  29482. updatable: updatable
  29483. };
  29484. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29485. };
  29486. /**
  29487. * Creates a box mesh.
  29488. * Please consider using the same method from the MeshBuilder class instead.
  29489. * The parameter `size` sets the size (float) of each box side (default 1).
  29490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29493. */
  29494. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29495. if (scene === void 0) { scene = null; }
  29496. var options = {
  29497. size: size,
  29498. sideOrientation: sideOrientation,
  29499. updatable: updatable
  29500. };
  29501. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29502. };
  29503. /**
  29504. * Creates a sphere mesh.
  29505. * Please consider using the same method from the MeshBuilder class instead.
  29506. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29507. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29511. */
  29512. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29513. var options = {
  29514. segments: segments,
  29515. diameterX: diameter,
  29516. diameterY: diameter,
  29517. diameterZ: diameter,
  29518. sideOrientation: sideOrientation,
  29519. updatable: updatable
  29520. };
  29521. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29522. };
  29523. /**
  29524. * Creates a cylinder or a cone mesh.
  29525. * Please consider using the same method from the MeshBuilder class instead.
  29526. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29527. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29528. * 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.
  29529. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29530. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29534. */
  29535. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29536. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29537. if (scene !== undefined) {
  29538. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29539. updatable = scene;
  29540. }
  29541. scene = subdivisions;
  29542. subdivisions = 1;
  29543. }
  29544. var options = {
  29545. height: height,
  29546. diameterTop: diameterTop,
  29547. diameterBottom: diameterBottom,
  29548. tessellation: tessellation,
  29549. subdivisions: subdivisions,
  29550. sideOrientation: sideOrientation,
  29551. updatable: updatable
  29552. };
  29553. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29554. };
  29555. // Torus (Code from SharpDX.org)
  29556. /**
  29557. * Creates a torus mesh.
  29558. * Please consider using the same method from the MeshBuilder class instead.
  29559. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29560. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29561. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29565. */
  29566. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29567. var options = {
  29568. diameter: diameter,
  29569. thickness: thickness,
  29570. tessellation: tessellation,
  29571. sideOrientation: sideOrientation,
  29572. updatable: updatable
  29573. };
  29574. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29575. };
  29576. /**
  29577. * Creates a torus knot mesh.
  29578. * Please consider using the same method from the MeshBuilder class instead.
  29579. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29580. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29581. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29582. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29586. */
  29587. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29588. var options = {
  29589. radius: radius,
  29590. tube: tube,
  29591. radialSegments: radialSegments,
  29592. tubularSegments: tubularSegments,
  29593. p: p,
  29594. q: q,
  29595. sideOrientation: sideOrientation,
  29596. updatable: updatable
  29597. };
  29598. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29599. };
  29600. /**
  29601. * Creates a line mesh.
  29602. * Please consider using the same method from the MeshBuilder class instead.
  29603. * 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.
  29604. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29605. * The parameter `points` is an array successive Vector3.
  29606. * 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
  29607. * When updating an instance, remember that only point positions can change, not the number of points.
  29608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29609. */
  29610. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29611. if (scene === void 0) { scene = null; }
  29612. if (updatable === void 0) { updatable = false; }
  29613. if (instance === void 0) { instance = null; }
  29614. var options = {
  29615. points: points,
  29616. updatable: updatable,
  29617. instance: instance
  29618. };
  29619. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29620. };
  29621. /**
  29622. * Creates a dashed line mesh.
  29623. * Please consider using the same method from the MeshBuilder class instead.
  29624. * 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.
  29625. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29626. * The parameter `points` is an array successive Vector3.
  29627. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29628. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29629. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29630. * 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
  29631. * When updating an instance, remember that only point positions can change, not the number of points.
  29632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29633. */
  29634. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29635. if (scene === void 0) { scene = null; }
  29636. var options = {
  29637. points: points,
  29638. dashSize: dashSize,
  29639. gapSize: gapSize,
  29640. dashNb: dashNb,
  29641. updatable: updatable,
  29642. instance: instance
  29643. };
  29644. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29645. };
  29646. /**
  29647. * Creates a polygon mesh.
  29648. * Please consider using the same method from the MeshBuilder class instead.
  29649. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29650. * 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.
  29651. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29653. * Remember you can only change the shape positions, not their number when updating a polygon.
  29654. */
  29655. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29656. var options = {
  29657. shape: shape,
  29658. holes: holes,
  29659. updatable: updatable,
  29660. sideOrientation: sideOrientation
  29661. };
  29662. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29663. };
  29664. /**
  29665. * Creates an extruded polygon mesh, with depth in the Y direction.
  29666. * Please consider using the same method from the MeshBuilder class instead.
  29667. */
  29668. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29669. var options = {
  29670. shape: shape,
  29671. holes: holes,
  29672. depth: depth,
  29673. updatable: updatable,
  29674. sideOrientation: sideOrientation
  29675. };
  29676. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29677. };
  29678. /**
  29679. * Creates an extruded shape mesh.
  29680. * 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.
  29681. * Please consider using the same method from the MeshBuilder class instead.
  29682. *
  29683. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29684. * 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
  29685. * extruded along the Z axis.
  29686. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29687. * 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.
  29688. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29689. * 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
  29690. * 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
  29691. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29695. */
  29696. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29697. if (scene === void 0) { scene = null; }
  29698. var options = {
  29699. shape: shape,
  29700. path: path,
  29701. scale: scale,
  29702. rotation: rotation,
  29703. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29704. sideOrientation: sideOrientation,
  29705. instance: instance,
  29706. updatable: updatable
  29707. };
  29708. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29709. };
  29710. /**
  29711. * Creates an custom extruded shape mesh.
  29712. * 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.
  29713. * Please consider using the same method from the MeshBuilder class instead.
  29714. *
  29715. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29716. * 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
  29717. * extruded along the Z axis.
  29718. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29719. * 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
  29720. * and the distance of this point from the begining of the path :
  29721. * ```javascript
  29722. * var rotationFunction = function(i, distance) {
  29723. * // do things
  29724. * return rotationValue; }
  29725. * ```
  29726. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29727. * 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
  29728. * and the distance of this point from the begining of the path :
  29729. * ```javascript
  29730. * var scaleFunction = function(i, distance) {
  29731. * // do things
  29732. * return scaleValue;}
  29733. * ```
  29734. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29735. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29736. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29737. * 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
  29738. * 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
  29739. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29743. */
  29744. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29745. var options = {
  29746. shape: shape,
  29747. path: path,
  29748. scaleFunction: scaleFunction,
  29749. rotationFunction: rotationFunction,
  29750. ribbonCloseArray: ribbonCloseArray,
  29751. ribbonClosePath: ribbonClosePath,
  29752. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29753. sideOrientation: sideOrientation,
  29754. instance: instance,
  29755. updatable: updatable
  29756. };
  29757. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29758. };
  29759. /**
  29760. * Creates lathe mesh.
  29761. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29762. * Please consider using the same method from the MeshBuilder class instead.
  29763. * 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
  29764. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29765. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29766. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29770. */
  29771. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29772. var options = {
  29773. shape: shape,
  29774. radius: radius,
  29775. tessellation: tessellation,
  29776. sideOrientation: sideOrientation,
  29777. updatable: updatable
  29778. };
  29779. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29780. };
  29781. /**
  29782. * Creates a plane mesh.
  29783. * Please consider using the same method from the MeshBuilder class instead.
  29784. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29788. */
  29789. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29790. var options = {
  29791. size: size,
  29792. width: size,
  29793. height: size,
  29794. sideOrientation: sideOrientation,
  29795. updatable: updatable
  29796. };
  29797. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29798. };
  29799. /**
  29800. * Creates a ground mesh.
  29801. * Please consider using the same method from the MeshBuilder class instead.
  29802. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29803. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29805. */
  29806. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29807. var options = {
  29808. width: width,
  29809. height: height,
  29810. subdivisions: subdivisions,
  29811. updatable: updatable
  29812. };
  29813. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29814. };
  29815. /**
  29816. * Creates a tiled ground mesh.
  29817. * Please consider using the same method from the MeshBuilder class instead.
  29818. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29819. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29820. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29821. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29822. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29823. * numbers of subdivisions on the ground width and height of each tile.
  29824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29825. */
  29826. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29827. var options = {
  29828. xmin: xmin,
  29829. zmin: zmin,
  29830. xmax: xmax,
  29831. zmax: zmax,
  29832. subdivisions: subdivisions,
  29833. precision: precision,
  29834. updatable: updatable
  29835. };
  29836. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29837. };
  29838. /**
  29839. * Creates a ground mesh from a height map.
  29840. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29841. * Please consider using the same method from the MeshBuilder class instead.
  29842. * The parameter `url` sets the URL of the height map image resource.
  29843. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29844. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29845. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29846. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29847. * 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).
  29848. * This function is passed the newly built mesh :
  29849. * ```javascript
  29850. * function(mesh) { // do things
  29851. * return; }
  29852. * ```
  29853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29854. */
  29855. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29856. var options = {
  29857. width: width,
  29858. height: height,
  29859. subdivisions: subdivisions,
  29860. minHeight: minHeight,
  29861. maxHeight: maxHeight,
  29862. updatable: updatable,
  29863. onReady: onReady
  29864. };
  29865. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29866. };
  29867. /**
  29868. * Creates a tube mesh.
  29869. * 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.
  29870. * Please consider using the same method from the MeshBuilder class instead.
  29871. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29872. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29873. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29874. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29875. * 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.
  29876. * It must return a radius value (positive float) :
  29877. * ```javascript
  29878. * var radiusFunction = function(i, distance) {
  29879. * // do things
  29880. * return radius; }
  29881. * ```
  29882. * 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
  29883. * 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
  29884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29887. */
  29888. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29889. var options = {
  29890. path: path,
  29891. radius: radius,
  29892. tessellation: tessellation,
  29893. radiusFunction: radiusFunction,
  29894. arc: 1,
  29895. cap: cap,
  29896. updatable: updatable,
  29897. sideOrientation: sideOrientation,
  29898. instance: instance
  29899. };
  29900. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29901. };
  29902. /**
  29903. * Creates a polyhedron mesh.
  29904. * Please consider using the same method from the MeshBuilder class instead.
  29905. * 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
  29906. * to choose the wanted type.
  29907. * The parameter `size` (positive float, default 1) sets the polygon size.
  29908. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29909. * 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`.
  29910. * 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
  29911. * 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)`).
  29912. * 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
  29913. * 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.
  29914. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29917. */
  29918. Mesh.CreatePolyhedron = function (name, options, scene) {
  29919. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29920. };
  29921. /**
  29922. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29923. * Please consider using the same method from the MeshBuilder class instead.
  29924. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29925. * 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`).
  29926. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29927. * 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.
  29928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29929. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29931. */
  29932. Mesh.CreateIcoSphere = function (name, options, scene) {
  29933. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29934. };
  29935. /**
  29936. * Creates a decal mesh.
  29937. * Please consider using the same method from the MeshBuilder class instead.
  29938. * 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.
  29939. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29940. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29941. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29942. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29943. */
  29944. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29945. var options = {
  29946. position: position,
  29947. normal: normal,
  29948. size: size,
  29949. angle: angle
  29950. };
  29951. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29952. };
  29953. // Skeletons
  29954. /**
  29955. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29956. */
  29957. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29958. if (!this._sourcePositions) {
  29959. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29960. if (!source) {
  29961. return this._sourcePositions;
  29962. }
  29963. this._sourcePositions = new Float32Array(source);
  29964. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29965. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29966. }
  29967. }
  29968. return this._sourcePositions;
  29969. };
  29970. /**
  29971. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29972. */
  29973. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29974. if (!this._sourceNormals) {
  29975. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29976. if (!source) {
  29977. return this._sourceNormals;
  29978. }
  29979. this._sourceNormals = new Float32Array(source);
  29980. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29981. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29982. }
  29983. }
  29984. return this._sourceNormals;
  29985. };
  29986. /**
  29987. * Updates the vertex buffer by applying transformation from the bones.
  29988. * Returns the Mesh.
  29989. *
  29990. * @param {skeleton} skeleton to apply
  29991. */
  29992. Mesh.prototype.applySkeleton = function (skeleton) {
  29993. if (!this.geometry) {
  29994. return this;
  29995. }
  29996. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29997. return this;
  29998. }
  29999. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30000. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30001. return this;
  30002. }
  30003. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30004. return this;
  30005. }
  30006. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30007. return this;
  30008. }
  30009. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30010. return this;
  30011. }
  30012. if (!this._sourcePositions) {
  30013. var submeshes = this.subMeshes.slice();
  30014. this.setPositionsForCPUSkinning();
  30015. this.subMeshes = submeshes;
  30016. }
  30017. if (!this._sourceNormals) {
  30018. this.setNormalsForCPUSkinning();
  30019. }
  30020. // positionsData checks for not being Float32Array will only pass at most once
  30021. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30022. if (!positionsData) {
  30023. return this;
  30024. }
  30025. if (!(positionsData instanceof Float32Array)) {
  30026. positionsData = new Float32Array(positionsData);
  30027. }
  30028. // normalsData checks for not being Float32Array will only pass at most once
  30029. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30030. if (!normalsData) {
  30031. return this;
  30032. }
  30033. if (!(normalsData instanceof Float32Array)) {
  30034. normalsData = new Float32Array(normalsData);
  30035. }
  30036. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30037. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30038. if (!matricesWeightsData || !matricesIndicesData) {
  30039. return this;
  30040. }
  30041. var needExtras = this.numBoneInfluencers > 4;
  30042. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30043. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30044. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30045. var tempVector3 = BABYLON.Vector3.Zero();
  30046. var finalMatrix = new BABYLON.Matrix();
  30047. var tempMatrix = new BABYLON.Matrix();
  30048. var matWeightIdx = 0;
  30049. var inf;
  30050. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30051. var weight;
  30052. for (inf = 0; inf < 4; inf++) {
  30053. weight = matricesWeightsData[matWeightIdx + inf];
  30054. if (weight > 0) {
  30055. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30056. finalMatrix.addToSelf(tempMatrix);
  30057. }
  30058. else
  30059. break;
  30060. }
  30061. if (needExtras) {
  30062. for (inf = 0; inf < 4; inf++) {
  30063. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30064. if (weight > 0) {
  30065. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30066. finalMatrix.addToSelf(tempMatrix);
  30067. }
  30068. else
  30069. break;
  30070. }
  30071. }
  30072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30073. tempVector3.toArray(positionsData, index);
  30074. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30075. tempVector3.toArray(normalsData, index);
  30076. finalMatrix.reset();
  30077. }
  30078. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30079. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30080. return this;
  30081. };
  30082. // Tools
  30083. /**
  30084. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30085. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30086. */
  30087. Mesh.MinMax = function (meshes) {
  30088. var minVector = null;
  30089. var maxVector = null;
  30090. meshes.forEach(function (mesh, index, array) {
  30091. var boundingInfo = mesh.getBoundingInfo();
  30092. var boundingBox = boundingInfo.boundingBox;
  30093. if (!minVector || !maxVector) {
  30094. minVector = boundingBox.minimumWorld;
  30095. maxVector = boundingBox.maximumWorld;
  30096. }
  30097. else {
  30098. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30099. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30100. }
  30101. });
  30102. if (!minVector || !maxVector) {
  30103. return {
  30104. min: BABYLON.Vector3.Zero(),
  30105. max: BABYLON.Vector3.Zero()
  30106. };
  30107. }
  30108. return {
  30109. min: minVector,
  30110. max: maxVector
  30111. };
  30112. };
  30113. /**
  30114. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30115. */
  30116. Mesh.Center = function (meshesOrMinMaxVector) {
  30117. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30118. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30119. };
  30120. /**
  30121. * Merge the array of meshes into a single mesh for performance reasons.
  30122. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30123. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30124. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30125. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30126. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30127. */
  30128. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30129. if (disposeSource === void 0) { disposeSource = true; }
  30130. var index;
  30131. if (!allow32BitsIndices) {
  30132. var totalVertices = 0;
  30133. // Counting vertices
  30134. for (index = 0; index < meshes.length; index++) {
  30135. if (meshes[index]) {
  30136. totalVertices += meshes[index].getTotalVertices();
  30137. if (totalVertices > 65536) {
  30138. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30139. return null;
  30140. }
  30141. }
  30142. }
  30143. }
  30144. // Merge
  30145. var vertexData = null;
  30146. var otherVertexData;
  30147. var indiceArray = new Array();
  30148. var source = null;
  30149. for (index = 0; index < meshes.length; index++) {
  30150. if (meshes[index]) {
  30151. meshes[index].computeWorldMatrix(true);
  30152. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30153. otherVertexData.transform(meshes[index].getWorldMatrix());
  30154. if (vertexData) {
  30155. vertexData.merge(otherVertexData);
  30156. }
  30157. else {
  30158. vertexData = otherVertexData;
  30159. source = meshes[index];
  30160. }
  30161. if (subdivideWithSubMeshes) {
  30162. indiceArray.push(meshes[index].getTotalIndices());
  30163. }
  30164. }
  30165. }
  30166. source = source;
  30167. if (!meshSubclass) {
  30168. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30169. }
  30170. vertexData.applyToMesh(meshSubclass);
  30171. // Setting properties
  30172. meshSubclass.material = source.material;
  30173. meshSubclass.checkCollisions = source.checkCollisions;
  30174. // Cleaning
  30175. if (disposeSource) {
  30176. for (index = 0; index < meshes.length; index++) {
  30177. if (meshes[index]) {
  30178. meshes[index].dispose();
  30179. }
  30180. }
  30181. }
  30182. // Subdivide
  30183. if (subdivideWithSubMeshes) {
  30184. //-- Suppresions du submesh global
  30185. meshSubclass.releaseSubMeshes();
  30186. index = 0;
  30187. var offset = 0;
  30188. //-- aplique la subdivision en fonction du tableau d'indices
  30189. while (index < indiceArray.length) {
  30190. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30191. offset += indiceArray[index];
  30192. index++;
  30193. }
  30194. }
  30195. return meshSubclass;
  30196. };
  30197. // Consts
  30198. Mesh._FRONTSIDE = 0;
  30199. Mesh._BACKSIDE = 1;
  30200. Mesh._DOUBLESIDE = 2;
  30201. Mesh._DEFAULTSIDE = 0;
  30202. Mesh._NO_CAP = 0;
  30203. Mesh._CAP_START = 1;
  30204. Mesh._CAP_END = 2;
  30205. Mesh._CAP_ALL = 3;
  30206. return Mesh;
  30207. }(BABYLON.AbstractMesh));
  30208. BABYLON.Mesh = Mesh;
  30209. })(BABYLON || (BABYLON = {}));
  30210. //# sourceMappingURL=babylon.mesh.js.map
  30211. var BABYLON;
  30212. (function (BABYLON) {
  30213. var BaseSubMesh = /** @class */ (function () {
  30214. function BaseSubMesh() {
  30215. }
  30216. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30217. get: function () {
  30218. return this._materialEffect;
  30219. },
  30220. enumerable: true,
  30221. configurable: true
  30222. });
  30223. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30224. if (defines === void 0) { defines = null; }
  30225. if (this._materialEffect === effect) {
  30226. if (!effect) {
  30227. this._materialDefines = null;
  30228. }
  30229. return;
  30230. }
  30231. this._materialDefines = defines;
  30232. this._materialEffect = effect;
  30233. };
  30234. return BaseSubMesh;
  30235. }());
  30236. BABYLON.BaseSubMesh = BaseSubMesh;
  30237. var SubMesh = /** @class */ (function (_super) {
  30238. __extends(SubMesh, _super);
  30239. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30240. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30241. var _this = _super.call(this) || this;
  30242. _this.materialIndex = materialIndex;
  30243. _this.verticesStart = verticesStart;
  30244. _this.verticesCount = verticesCount;
  30245. _this.indexStart = indexStart;
  30246. _this.indexCount = indexCount;
  30247. _this._renderId = 0;
  30248. _this._mesh = mesh;
  30249. _this._renderingMesh = renderingMesh || mesh;
  30250. mesh.subMeshes.push(_this);
  30251. _this._trianglePlanes = [];
  30252. _this._id = mesh.subMeshes.length - 1;
  30253. if (createBoundingBox) {
  30254. _this.refreshBoundingInfo();
  30255. mesh.computeWorldMatrix(true);
  30256. }
  30257. return _this;
  30258. }
  30259. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30260. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30261. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30262. };
  30263. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30264. get: function () {
  30265. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30266. },
  30267. enumerable: true,
  30268. configurable: true
  30269. });
  30270. /**
  30271. * Returns the submesh BoudingInfo object.
  30272. */
  30273. SubMesh.prototype.getBoundingInfo = function () {
  30274. if (this.IsGlobal) {
  30275. return this._mesh.getBoundingInfo();
  30276. }
  30277. return this._boundingInfo;
  30278. };
  30279. /**
  30280. * Sets the submesh BoundingInfo.
  30281. * Return the SubMesh.
  30282. */
  30283. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30284. this._boundingInfo = boundingInfo;
  30285. return this;
  30286. };
  30287. /**
  30288. * Returns the mesh of the current submesh.
  30289. */
  30290. SubMesh.prototype.getMesh = function () {
  30291. return this._mesh;
  30292. };
  30293. /**
  30294. * Returns the rendering mesh of the submesh.
  30295. */
  30296. SubMesh.prototype.getRenderingMesh = function () {
  30297. return this._renderingMesh;
  30298. };
  30299. /**
  30300. * Returns the submesh material.
  30301. */
  30302. SubMesh.prototype.getMaterial = function () {
  30303. var rootMaterial = this._renderingMesh.material;
  30304. if (rootMaterial === null || rootMaterial === undefined) {
  30305. return this._mesh.getScene().defaultMaterial;
  30306. }
  30307. else if (rootMaterial.getSubMaterial) {
  30308. var multiMaterial = rootMaterial;
  30309. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30310. if (this._currentMaterial !== effectiveMaterial) {
  30311. this._currentMaterial = effectiveMaterial;
  30312. this._materialDefines = null;
  30313. }
  30314. return effectiveMaterial;
  30315. }
  30316. return rootMaterial;
  30317. };
  30318. // Methods
  30319. /**
  30320. * Sets a new updated BoundingInfo object to the submesh.
  30321. * Returns the SubMesh.
  30322. */
  30323. SubMesh.prototype.refreshBoundingInfo = function () {
  30324. this._lastColliderWorldVertices = null;
  30325. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30326. return this;
  30327. }
  30328. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30329. if (!data) {
  30330. this._boundingInfo = this._mesh.getBoundingInfo();
  30331. return this;
  30332. }
  30333. var indices = this._renderingMesh.getIndices();
  30334. var extend;
  30335. //is this the only submesh?
  30336. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30337. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30338. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30339. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30340. }
  30341. else {
  30342. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30343. }
  30344. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30345. return this;
  30346. };
  30347. SubMesh.prototype._checkCollision = function (collider) {
  30348. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30349. return boundingInfo._checkCollision(collider);
  30350. };
  30351. /**
  30352. * Updates the submesh BoundingInfo.
  30353. * Returns the Submesh.
  30354. */
  30355. SubMesh.prototype.updateBoundingInfo = function (world) {
  30356. var boundingInfo = this.getBoundingInfo();
  30357. if (!boundingInfo) {
  30358. this.refreshBoundingInfo();
  30359. boundingInfo = this.getBoundingInfo();
  30360. }
  30361. boundingInfo.update(world);
  30362. return this;
  30363. };
  30364. /**
  30365. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30366. * Boolean returned.
  30367. */
  30368. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30369. var boundingInfo = this.getBoundingInfo();
  30370. if (!boundingInfo) {
  30371. return false;
  30372. }
  30373. return boundingInfo.isInFrustum(frustumPlanes);
  30374. };
  30375. /**
  30376. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30377. * Boolean returned.
  30378. */
  30379. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30380. var boundingInfo = this.getBoundingInfo();
  30381. if (!boundingInfo) {
  30382. return false;
  30383. }
  30384. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30385. };
  30386. /**
  30387. * Renders the submesh.
  30388. * Returns it.
  30389. */
  30390. SubMesh.prototype.render = function (enableAlphaMode) {
  30391. this._renderingMesh.render(this, enableAlphaMode);
  30392. return this;
  30393. };
  30394. /**
  30395. * Returns a new Index Buffer.
  30396. * Type returned : WebGLBuffer.
  30397. */
  30398. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30399. if (!this._linesIndexBuffer) {
  30400. var linesIndices = [];
  30401. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30402. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30403. }
  30404. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30405. this.linesIndexCount = linesIndices.length;
  30406. }
  30407. return this._linesIndexBuffer;
  30408. };
  30409. /**
  30410. * True is the passed Ray intersects the submesh bounding box.
  30411. * Boolean returned.
  30412. */
  30413. SubMesh.prototype.canIntersects = function (ray) {
  30414. var boundingInfo = this.getBoundingInfo();
  30415. if (!boundingInfo) {
  30416. return false;
  30417. }
  30418. return ray.intersectsBox(boundingInfo.boundingBox);
  30419. };
  30420. /**
  30421. * Returns an object IntersectionInfo.
  30422. */
  30423. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30424. var intersectInfo = null;
  30425. // LineMesh first as it's also a Mesh...
  30426. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30427. var lineMesh = this._mesh;
  30428. // Line test
  30429. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30430. var p0 = positions[indices[index]];
  30431. var p1 = positions[indices[index + 1]];
  30432. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30433. if (length < 0) {
  30434. continue;
  30435. }
  30436. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30437. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30438. if (fastCheck) {
  30439. break;
  30440. }
  30441. }
  30442. }
  30443. }
  30444. else {
  30445. // Triangles test
  30446. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30447. var p0 = positions[indices[index]];
  30448. var p1 = positions[indices[index + 1]];
  30449. var p2 = positions[indices[index + 2]];
  30450. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30451. if (currentIntersectInfo) {
  30452. if (currentIntersectInfo.distance < 0) {
  30453. continue;
  30454. }
  30455. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30456. intersectInfo = currentIntersectInfo;
  30457. intersectInfo.faceId = index / 3;
  30458. if (fastCheck) {
  30459. break;
  30460. }
  30461. }
  30462. }
  30463. }
  30464. }
  30465. return intersectInfo;
  30466. };
  30467. SubMesh.prototype._rebuild = function () {
  30468. if (this._linesIndexBuffer) {
  30469. this._linesIndexBuffer = null;
  30470. }
  30471. };
  30472. // Clone
  30473. /**
  30474. * Creates a new Submesh from the passed Mesh.
  30475. */
  30476. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30477. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30478. if (!this.IsGlobal) {
  30479. var boundingInfo = this.getBoundingInfo();
  30480. if (!boundingInfo) {
  30481. return result;
  30482. }
  30483. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30484. }
  30485. return result;
  30486. };
  30487. // Dispose
  30488. /**
  30489. * Disposes the Submesh.
  30490. * Returns nothing.
  30491. */
  30492. SubMesh.prototype.dispose = function () {
  30493. if (this._linesIndexBuffer) {
  30494. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30495. this._linesIndexBuffer = null;
  30496. }
  30497. // Remove from mesh
  30498. var index = this._mesh.subMeshes.indexOf(this);
  30499. this._mesh.subMeshes.splice(index, 1);
  30500. };
  30501. // Statics
  30502. /**
  30503. * Creates a new Submesh from the passed parameters :
  30504. * - materialIndex (integer) : the index of the main mesh material.
  30505. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30506. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30507. * - mesh (Mesh) : the main mesh to create the submesh from.
  30508. * - renderingMesh (optional Mesh) : rendering mesh.
  30509. */
  30510. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30511. var minVertexIndex = Number.MAX_VALUE;
  30512. var maxVertexIndex = -Number.MAX_VALUE;
  30513. renderingMesh = (renderingMesh || mesh);
  30514. var indices = renderingMesh.getIndices();
  30515. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30516. var vertexIndex = indices[index];
  30517. if (vertexIndex < minVertexIndex)
  30518. minVertexIndex = vertexIndex;
  30519. if (vertexIndex > maxVertexIndex)
  30520. maxVertexIndex = vertexIndex;
  30521. }
  30522. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30523. };
  30524. return SubMesh;
  30525. }(BaseSubMesh));
  30526. BABYLON.SubMesh = SubMesh;
  30527. })(BABYLON || (BABYLON = {}));
  30528. //# sourceMappingURL=babylon.subMesh.js.map
  30529. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30530. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30531. s = arguments[i];
  30532. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30533. t[p] = s[p];
  30534. }
  30535. return t;
  30536. };
  30537. var BABYLON;
  30538. (function (BABYLON) {
  30539. /**
  30540. * Manages the defines for the Material.
  30541. */
  30542. var MaterialDefines = /** @class */ (function () {
  30543. function MaterialDefines() {
  30544. this._isDirty = true;
  30545. this._areLightsDirty = true;
  30546. this._areAttributesDirty = true;
  30547. this._areTexturesDirty = true;
  30548. this._areFresnelDirty = true;
  30549. this._areMiscDirty = true;
  30550. this._areImageProcessingDirty = true;
  30551. this._normals = false;
  30552. this._uvs = false;
  30553. this._needNormals = false;
  30554. this._needUVs = false;
  30555. }
  30556. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30557. /**
  30558. * Specifies if the material needs to be re-calculated.
  30559. */
  30560. get: function () {
  30561. return this._isDirty;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. /**
  30567. * Marks the material to indicate that it has been re-calculated.
  30568. */
  30569. MaterialDefines.prototype.markAsProcessed = function () {
  30570. this._isDirty = false;
  30571. this._areAttributesDirty = false;
  30572. this._areTexturesDirty = false;
  30573. this._areFresnelDirty = false;
  30574. this._areLightsDirty = false;
  30575. this._areMiscDirty = false;
  30576. this._areImageProcessingDirty = false;
  30577. };
  30578. /**
  30579. * Marks the material to indicate that it needs to be re-calculated.
  30580. */
  30581. MaterialDefines.prototype.markAsUnprocessed = function () {
  30582. this._isDirty = true;
  30583. };
  30584. /**
  30585. * Marks the material to indicate all of its defines need to be re-calculated.
  30586. */
  30587. MaterialDefines.prototype.markAllAsDirty = function () {
  30588. this._areTexturesDirty = true;
  30589. this._areAttributesDirty = true;
  30590. this._areLightsDirty = true;
  30591. this._areFresnelDirty = true;
  30592. this._areMiscDirty = true;
  30593. this._areImageProcessingDirty = true;
  30594. this._isDirty = true;
  30595. };
  30596. /**
  30597. * Marks the material to indicate that image processing needs to be re-calculated.
  30598. */
  30599. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30600. this._areImageProcessingDirty = true;
  30601. this._isDirty = true;
  30602. };
  30603. /**
  30604. * Marks the material to indicate the lights need to be re-calculated.
  30605. */
  30606. MaterialDefines.prototype.markAsLightDirty = function () {
  30607. this._areLightsDirty = true;
  30608. this._isDirty = true;
  30609. };
  30610. /**
  30611. * Marks the attribute state as changed.
  30612. */
  30613. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30614. this._areAttributesDirty = true;
  30615. this._isDirty = true;
  30616. };
  30617. /**
  30618. * Marks the texture state as changed.
  30619. */
  30620. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30621. this._areTexturesDirty = true;
  30622. this._isDirty = true;
  30623. };
  30624. /**
  30625. * Marks the fresnel state as changed.
  30626. */
  30627. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30628. this._areFresnelDirty = true;
  30629. this._isDirty = true;
  30630. };
  30631. /**
  30632. * Marks the misc state as changed.
  30633. */
  30634. MaterialDefines.prototype.markAsMiscDirty = function () {
  30635. this._areMiscDirty = true;
  30636. this._isDirty = true;
  30637. };
  30638. /**
  30639. * Rebuilds the material defines.
  30640. */
  30641. MaterialDefines.prototype.rebuild = function () {
  30642. if (this._keys) {
  30643. delete this._keys;
  30644. }
  30645. this._keys = [];
  30646. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30647. var key = _a[_i];
  30648. if (key[0] === "_") {
  30649. continue;
  30650. }
  30651. this._keys.push(key);
  30652. }
  30653. };
  30654. /**
  30655. * Specifies if two material defines are equal.
  30656. * @param other - A material define instance to compare to.
  30657. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30658. */
  30659. MaterialDefines.prototype.isEqual = function (other) {
  30660. if (this._keys.length !== other._keys.length) {
  30661. return false;
  30662. }
  30663. for (var index = 0; index < this._keys.length; index++) {
  30664. var prop = this._keys[index];
  30665. if (this[prop] !== other[prop]) {
  30666. return false;
  30667. }
  30668. }
  30669. return true;
  30670. };
  30671. /**
  30672. * Clones this instance's defines to another instance.
  30673. * @param other - material defines to clone values to.
  30674. */
  30675. MaterialDefines.prototype.cloneTo = function (other) {
  30676. if (this._keys.length !== other._keys.length) {
  30677. other._keys = this._keys.slice(0);
  30678. }
  30679. for (var index = 0; index < this._keys.length; index++) {
  30680. var prop = this._keys[index];
  30681. other[prop] = this[prop];
  30682. }
  30683. };
  30684. /**
  30685. * Resets the material define values.
  30686. */
  30687. MaterialDefines.prototype.reset = function () {
  30688. for (var index = 0; index < this._keys.length; index++) {
  30689. var prop = this._keys[index];
  30690. if (typeof (this[prop]) === "number") {
  30691. this[prop] = 0;
  30692. }
  30693. else {
  30694. this[prop] = false;
  30695. }
  30696. }
  30697. };
  30698. /**
  30699. * Converts the material define values to a string.
  30700. * @returns - String of material define information.
  30701. */
  30702. MaterialDefines.prototype.toString = function () {
  30703. var result = "";
  30704. for (var index = 0; index < this._keys.length; index++) {
  30705. var prop = this._keys[index];
  30706. var value = this[prop];
  30707. if (typeof (value) === "number") {
  30708. result += "#define " + prop + " " + this[prop] + "\n";
  30709. }
  30710. else if (value) {
  30711. result += "#define " + prop + "\n";
  30712. }
  30713. }
  30714. return result;
  30715. };
  30716. return MaterialDefines;
  30717. }());
  30718. BABYLON.MaterialDefines = MaterialDefines;
  30719. /**
  30720. * This offers the main features of a material in BJS.
  30721. */
  30722. var Material = /** @class */ (function () {
  30723. /**
  30724. * Creates a material instance.
  30725. * @param name - The name of the material.
  30726. * @param scene - The BJS scene to reference.
  30727. * @param doNotAdd - Specifies if the material should be added to the scene.
  30728. */
  30729. function Material(name, scene, doNotAdd) {
  30730. /**
  30731. * Specifies if the ready state should be checked on each call.
  30732. */
  30733. this.checkReadyOnEveryCall = false;
  30734. /**
  30735. * Specifies if the ready state should be checked once.
  30736. */
  30737. this.checkReadyOnlyOnce = false;
  30738. /**
  30739. * The state of the material.
  30740. */
  30741. this.state = "";
  30742. /**
  30743. * The alpha value of the material.
  30744. */
  30745. this._alpha = 1.0;
  30746. /**
  30747. * Specifies if back face culling is enabled.
  30748. */
  30749. this._backFaceCulling = true;
  30750. /**
  30751. * Specifies if the material should be serialized.
  30752. */
  30753. this.doNotSerialize = false;
  30754. /**
  30755. * Specifies if the effect should be stored on sub meshes.
  30756. */
  30757. this.storeEffectOnSubMeshes = false;
  30758. /**
  30759. * An event triggered when the material is disposed.
  30760. * @type {BABYLON.Observable}
  30761. */
  30762. this.onDisposeObservable = new BABYLON.Observable();
  30763. /**
  30764. * An event triggered when the material is bound.
  30765. * @type {BABYLON.Observable}
  30766. */
  30767. this.onBindObservable = new BABYLON.Observable();
  30768. /**
  30769. * An event triggered when the material is unbound.
  30770. * @type {BABYLON.Observable}
  30771. */
  30772. this.onUnBindObservable = new BABYLON.Observable();
  30773. /**
  30774. * Stores the value of the alpha mode.
  30775. */
  30776. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30777. /**
  30778. * Stores the state of the need depth pre-pass value.
  30779. */
  30780. this._needDepthPrePass = false;
  30781. /**
  30782. * Specifies if depth writing should be disabled.
  30783. */
  30784. this.disableDepthWrite = false;
  30785. /**
  30786. * Specifies if depth writing should be forced.
  30787. */
  30788. this.forceDepthWrite = false;
  30789. /**
  30790. * Specifies if there should be a separate pass for culling.
  30791. */
  30792. this.separateCullingPass = false;
  30793. /**
  30794. * Stores the state specifing if fog should be enabled.
  30795. */
  30796. this._fogEnabled = true;
  30797. /**
  30798. * Stores the size of points.
  30799. */
  30800. this.pointSize = 1.0;
  30801. /**
  30802. * Stores the z offset value.
  30803. */
  30804. this.zOffset = 0;
  30805. /**
  30806. * Specifies if the material was previously ready.
  30807. */
  30808. this._wasPreviouslyReady = false;
  30809. /**
  30810. * Stores the fill mode state.
  30811. */
  30812. this._fillMode = Material.TriangleFillMode;
  30813. this.name = name;
  30814. this.id = name || BABYLON.Tools.RandomId();
  30815. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30816. if (this._scene.useRightHandedSystem) {
  30817. this.sideOrientation = Material.ClockWiseSideOrientation;
  30818. }
  30819. else {
  30820. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30821. }
  30822. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30823. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30824. if (!doNotAdd) {
  30825. this._scene.materials.push(this);
  30826. }
  30827. }
  30828. Object.defineProperty(Material, "TriangleFillMode", {
  30829. /**
  30830. * Returns the triangle fill mode.
  30831. */
  30832. get: function () {
  30833. return Material._TriangleFillMode;
  30834. },
  30835. enumerable: true,
  30836. configurable: true
  30837. });
  30838. Object.defineProperty(Material, "WireFrameFillMode", {
  30839. /**
  30840. * Returns the wireframe mode.
  30841. */
  30842. get: function () {
  30843. return Material._WireFrameFillMode;
  30844. },
  30845. enumerable: true,
  30846. configurable: true
  30847. });
  30848. Object.defineProperty(Material, "PointFillMode", {
  30849. /**
  30850. * Returns the point fill mode.
  30851. */
  30852. get: function () {
  30853. return Material._PointFillMode;
  30854. },
  30855. enumerable: true,
  30856. configurable: true
  30857. });
  30858. Object.defineProperty(Material, "PointListDrawMode", {
  30859. /**
  30860. * Returns the point list draw mode.
  30861. */
  30862. get: function () {
  30863. return Material._PointListDrawMode;
  30864. },
  30865. enumerable: true,
  30866. configurable: true
  30867. });
  30868. Object.defineProperty(Material, "LineListDrawMode", {
  30869. /**
  30870. * Returns the line list draw mode.
  30871. */
  30872. get: function () {
  30873. return Material._LineListDrawMode;
  30874. },
  30875. enumerable: true,
  30876. configurable: true
  30877. });
  30878. Object.defineProperty(Material, "LineLoopDrawMode", {
  30879. /**
  30880. * Returns the line loop draw mode.
  30881. */
  30882. get: function () {
  30883. return Material._LineLoopDrawMode;
  30884. },
  30885. enumerable: true,
  30886. configurable: true
  30887. });
  30888. Object.defineProperty(Material, "LineStripDrawMode", {
  30889. /**
  30890. * Returns the line strip draw mode.
  30891. */
  30892. get: function () {
  30893. return Material._LineStripDrawMode;
  30894. },
  30895. enumerable: true,
  30896. configurable: true
  30897. });
  30898. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30899. /**
  30900. * Returns the triangle strip draw mode.
  30901. */
  30902. get: function () {
  30903. return Material._TriangleStripDrawMode;
  30904. },
  30905. enumerable: true,
  30906. configurable: true
  30907. });
  30908. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30909. /**
  30910. * Returns the triangle fan draw mode.
  30911. */
  30912. get: function () {
  30913. return Material._TriangleFanDrawMode;
  30914. },
  30915. enumerable: true,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30919. /**
  30920. * Returns the clock-wise side orientation.
  30921. */
  30922. get: function () {
  30923. return Material._ClockWiseSideOrientation;
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30929. /**
  30930. * Returns the counter clock-wise side orientation.
  30931. */
  30932. get: function () {
  30933. return Material._CounterClockWiseSideOrientation;
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. Object.defineProperty(Material, "TextureDirtyFlag", {
  30939. /**
  30940. * Returns the dirty texture flag value.
  30941. */
  30942. get: function () {
  30943. return Material._TextureDirtyFlag;
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. Object.defineProperty(Material, "LightDirtyFlag", {
  30949. /**
  30950. * Returns the dirty light flag value.
  30951. */
  30952. get: function () {
  30953. return Material._LightDirtyFlag;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30959. /**
  30960. * Returns the dirty fresnel flag value.
  30961. */
  30962. get: function () {
  30963. return Material._FresnelDirtyFlag;
  30964. },
  30965. enumerable: true,
  30966. configurable: true
  30967. });
  30968. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30969. /**
  30970. * Returns the dirty attributes flag value.
  30971. */
  30972. get: function () {
  30973. return Material._AttributesDirtyFlag;
  30974. },
  30975. enumerable: true,
  30976. configurable: true
  30977. });
  30978. Object.defineProperty(Material, "MiscDirtyFlag", {
  30979. /**
  30980. * Returns the dirty misc flag value.
  30981. */
  30982. get: function () {
  30983. return Material._MiscDirtyFlag;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(Material.prototype, "alpha", {
  30989. /**
  30990. * Gets the alpha value of the material.
  30991. */
  30992. get: function () {
  30993. return this._alpha;
  30994. },
  30995. /**
  30996. * Sets the alpha value of the material.
  30997. */
  30998. set: function (value) {
  30999. if (this._alpha === value) {
  31000. return;
  31001. }
  31002. this._alpha = value;
  31003. this.markAsDirty(Material.MiscDirtyFlag);
  31004. },
  31005. enumerable: true,
  31006. configurable: true
  31007. });
  31008. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31009. /**
  31010. * Gets the back-face culling state.
  31011. */
  31012. get: function () {
  31013. return this._backFaceCulling;
  31014. },
  31015. /**
  31016. * Sets the back-face culling state.
  31017. */
  31018. set: function (value) {
  31019. if (this._backFaceCulling === value) {
  31020. return;
  31021. }
  31022. this._backFaceCulling = value;
  31023. this.markAsDirty(Material.TextureDirtyFlag);
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Material.prototype, "onDispose", {
  31029. /**
  31030. * Called during a dispose event.
  31031. */
  31032. set: function (callback) {
  31033. if (this._onDisposeObserver) {
  31034. this.onDisposeObservable.remove(this._onDisposeObserver);
  31035. }
  31036. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31037. },
  31038. enumerable: true,
  31039. configurable: true
  31040. });
  31041. Object.defineProperty(Material.prototype, "onBind", {
  31042. /**
  31043. * Called during a bind event.
  31044. */
  31045. set: function (callback) {
  31046. if (this._onBindObserver) {
  31047. this.onBindObservable.remove(this._onBindObserver);
  31048. }
  31049. this._onBindObserver = this.onBindObservable.add(callback);
  31050. },
  31051. enumerable: true,
  31052. configurable: true
  31053. });
  31054. Object.defineProperty(Material.prototype, "alphaMode", {
  31055. /**
  31056. * Gets the value of the alpha mode.
  31057. */
  31058. get: function () {
  31059. return this._alphaMode;
  31060. },
  31061. /**
  31062. * Sets the value of the alpha mode.
  31063. */
  31064. set: function (value) {
  31065. if (this._alphaMode === value) {
  31066. return;
  31067. }
  31068. this._alphaMode = value;
  31069. this.markAsDirty(Material.TextureDirtyFlag);
  31070. },
  31071. enumerable: true,
  31072. configurable: true
  31073. });
  31074. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31075. /**
  31076. * Gets the depth pre-pass value.
  31077. */
  31078. get: function () {
  31079. return this._needDepthPrePass;
  31080. },
  31081. /**
  31082. * Sets the need depth pre-pass value.
  31083. */
  31084. set: function (value) {
  31085. if (this._needDepthPrePass === value) {
  31086. return;
  31087. }
  31088. this._needDepthPrePass = value;
  31089. if (this._needDepthPrePass) {
  31090. this.checkReadyOnEveryCall = true;
  31091. }
  31092. },
  31093. enumerable: true,
  31094. configurable: true
  31095. });
  31096. Object.defineProperty(Material.prototype, "fogEnabled", {
  31097. /**
  31098. * Gets the value of the fog enabled state.
  31099. */
  31100. get: function () {
  31101. return this._fogEnabled;
  31102. },
  31103. /**
  31104. * Sets the state for enabling fog.
  31105. */
  31106. set: function (value) {
  31107. if (this._fogEnabled === value) {
  31108. return;
  31109. }
  31110. this._fogEnabled = value;
  31111. this.markAsDirty(Material.MiscDirtyFlag);
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Material.prototype, "wireframe", {
  31117. /**
  31118. * Gets a value specifying if wireframe mode is enabled.
  31119. */
  31120. get: function () {
  31121. return this._fillMode === Material.WireFrameFillMode;
  31122. },
  31123. /**
  31124. * Sets the state of wireframe mode.
  31125. */
  31126. set: function (value) {
  31127. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31128. },
  31129. enumerable: true,
  31130. configurable: true
  31131. });
  31132. Object.defineProperty(Material.prototype, "pointsCloud", {
  31133. /**
  31134. * Gets the value specifying if point clouds are enabled.
  31135. */
  31136. get: function () {
  31137. return this._fillMode === Material.PointFillMode;
  31138. },
  31139. /**
  31140. * Sets the state of point cloud mode.
  31141. */
  31142. set: function (value) {
  31143. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Material.prototype, "fillMode", {
  31149. /**
  31150. * Gets the material fill mode.
  31151. */
  31152. get: function () {
  31153. return this._fillMode;
  31154. },
  31155. /**
  31156. * Sets the material fill mode.
  31157. */
  31158. set: function (value) {
  31159. if (this._fillMode === value) {
  31160. return;
  31161. }
  31162. this._fillMode = value;
  31163. this.markAsDirty(Material.MiscDirtyFlag);
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. /**
  31169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31170. * subclasses should override adding information pertainent to themselves.
  31171. * @returns - String with material information.
  31172. */
  31173. Material.prototype.toString = function (fullDetails) {
  31174. var ret = "Name: " + this.name;
  31175. if (fullDetails) {
  31176. }
  31177. return ret;
  31178. };
  31179. /**
  31180. * Gets the class name of the material.
  31181. * @returns - String with the class name of the material.
  31182. */
  31183. Material.prototype.getClassName = function () {
  31184. return "Material";
  31185. };
  31186. Object.defineProperty(Material.prototype, "isFrozen", {
  31187. /**
  31188. * Specifies if updates for the material been locked.
  31189. */
  31190. get: function () {
  31191. return this.checkReadyOnlyOnce;
  31192. },
  31193. enumerable: true,
  31194. configurable: true
  31195. });
  31196. /**
  31197. * Locks updates for the material.
  31198. */
  31199. Material.prototype.freeze = function () {
  31200. this.checkReadyOnlyOnce = true;
  31201. };
  31202. /**
  31203. * Unlocks updates for the material.
  31204. */
  31205. Material.prototype.unfreeze = function () {
  31206. this.checkReadyOnlyOnce = false;
  31207. };
  31208. /**
  31209. * Specifies if the material is ready to be used.
  31210. * @param mesh - BJS mesh.
  31211. * @param useInstances - Specifies if instances should be used.
  31212. * @returns - Boolean indicating if the material is ready to be used.
  31213. */
  31214. Material.prototype.isReady = function (mesh, useInstances) {
  31215. return true;
  31216. };
  31217. /**
  31218. * Specifies that the submesh is ready to be used.
  31219. * @param mesh - BJS mesh.
  31220. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31221. * @param useInstances - Specifies that instances should be used.
  31222. * @returns - boolean indicating that the submesh is ready or not.
  31223. */
  31224. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31225. return false;
  31226. };
  31227. /**
  31228. * Returns the material effect.
  31229. * @returns - Nullable material effect.
  31230. */
  31231. Material.prototype.getEffect = function () {
  31232. return this._effect;
  31233. };
  31234. /**
  31235. * Returns the BJS scene.
  31236. * @returns - BJS Scene.
  31237. */
  31238. Material.prototype.getScene = function () {
  31239. return this._scene;
  31240. };
  31241. /**
  31242. * Specifies if the material will require alpha blending
  31243. * @returns - Boolean specifying if alpha blending is needed.
  31244. */
  31245. Material.prototype.needAlphaBlending = function () {
  31246. return (this.alpha < 1.0);
  31247. };
  31248. /**
  31249. * Specifies if the mesh will require alpha blending.
  31250. * @param mesh - BJS mesh.
  31251. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31252. */
  31253. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31254. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31255. };
  31256. /**
  31257. * Specifies if this material should be rendered in alpha test mode.
  31258. * @returns - Boolean specifying if an alpha test is needed.
  31259. */
  31260. Material.prototype.needAlphaTesting = function () {
  31261. return false;
  31262. };
  31263. /**
  31264. * Gets the texture used for the alpha test.
  31265. * @returns - Nullable alpha test texture.
  31266. */
  31267. Material.prototype.getAlphaTestTexture = function () {
  31268. return null;
  31269. };
  31270. /**
  31271. * Marks the material to indicate that it needs to be re-calculated.
  31272. */
  31273. Material.prototype.markDirty = function () {
  31274. this._wasPreviouslyReady = false;
  31275. };
  31276. Material.prototype._preBind = function (effect, overrideOrientation) {
  31277. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31278. var engine = this._scene.getEngine();
  31279. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31280. var reverse = orientation === Material.ClockWiseSideOrientation;
  31281. engine.enableEffect(effect ? effect : this._effect);
  31282. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31283. return reverse;
  31284. };
  31285. /**
  31286. * Binds the material to the mesh.
  31287. * @param world - World transformation matrix.
  31288. * @param mesh - Mesh to bind the material to.
  31289. */
  31290. Material.prototype.bind = function (world, mesh) {
  31291. };
  31292. /**
  31293. * Binds the submesh to the material.
  31294. * @param world - World transformation matrix.
  31295. * @param mesh - Mesh containing the submesh.
  31296. * @param subMesh - Submesh to bind the material to.
  31297. */
  31298. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31299. };
  31300. /**
  31301. * Binds the world matrix to the material.
  31302. * @param world - World transformation matrix.
  31303. */
  31304. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31305. };
  31306. /**
  31307. * Binds the scene's uniform buffer to the effect.
  31308. * @param effect - Effect to bind to the scene uniform buffer.
  31309. * @param sceneUbo - Scene uniform buffer.
  31310. */
  31311. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31312. sceneUbo.bindToEffect(effect, "Scene");
  31313. };
  31314. /**
  31315. * Binds the view matrix to the effect.
  31316. * @param effect - Effect to bind the view matrix to.
  31317. */
  31318. Material.prototype.bindView = function (effect) {
  31319. if (!this._useUBO) {
  31320. effect.setMatrix("view", this.getScene().getViewMatrix());
  31321. }
  31322. else {
  31323. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31324. }
  31325. };
  31326. /**
  31327. * Binds the view projection matrix to the effect.
  31328. * @param effect - Effect to bind the view projection matrix to.
  31329. */
  31330. Material.prototype.bindViewProjection = function (effect) {
  31331. if (!this._useUBO) {
  31332. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31333. }
  31334. else {
  31335. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31336. }
  31337. };
  31338. /**
  31339. * Specifies if material alpha testing should be turned on for the mesh.
  31340. * @param mesh - BJS mesh.
  31341. */
  31342. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31343. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31344. };
  31345. /**
  31346. * Processes to execute after binding the material to a mesh.
  31347. * @param mesh - BJS mesh.
  31348. */
  31349. Material.prototype._afterBind = function (mesh) {
  31350. this._scene._cachedMaterial = this;
  31351. if (mesh) {
  31352. this._scene._cachedVisibility = mesh.visibility;
  31353. }
  31354. else {
  31355. this._scene._cachedVisibility = 1;
  31356. }
  31357. if (mesh) {
  31358. this.onBindObservable.notifyObservers(mesh);
  31359. }
  31360. if (this.disableDepthWrite) {
  31361. var engine = this._scene.getEngine();
  31362. this._cachedDepthWriteState = engine.getDepthWrite();
  31363. engine.setDepthWrite(false);
  31364. }
  31365. };
  31366. /**
  31367. * Unbinds the material from the mesh.
  31368. */
  31369. Material.prototype.unbind = function () {
  31370. this.onUnBindObservable.notifyObservers(this);
  31371. if (this.disableDepthWrite) {
  31372. var engine = this._scene.getEngine();
  31373. engine.setDepthWrite(this._cachedDepthWriteState);
  31374. }
  31375. };
  31376. /**
  31377. * Gets the active textures from the material.
  31378. * @returns - Array of textures.
  31379. */
  31380. Material.prototype.getActiveTextures = function () {
  31381. return [];
  31382. };
  31383. /**
  31384. * Specifies if the material uses a texture.
  31385. * @param texture - Texture to check against the material.
  31386. * @returns - Boolean specifying if the material uses the texture.
  31387. */
  31388. Material.prototype.hasTexture = function (texture) {
  31389. return false;
  31390. };
  31391. /**
  31392. * Makes a duplicate of the material, and gives it a new name.
  31393. * @param name - Name to call the duplicated material.
  31394. * @returns - Nullable cloned material
  31395. */
  31396. Material.prototype.clone = function (name) {
  31397. return null;
  31398. };
  31399. /**
  31400. * Gets the meshes bound to the material.
  31401. * @returns - Array of meshes bound to the material.
  31402. */
  31403. Material.prototype.getBindedMeshes = function () {
  31404. var result = new Array();
  31405. for (var index = 0; index < this._scene.meshes.length; index++) {
  31406. var mesh = this._scene.meshes[index];
  31407. if (mesh.material === this) {
  31408. result.push(mesh);
  31409. }
  31410. }
  31411. return result;
  31412. };
  31413. /**
  31414. * Force shader compilation
  31415. * @param mesh - BJS mesh.
  31416. * @param onCompiled - function to execute once the material is compiled.
  31417. * @param options - options to pass to this function.
  31418. */
  31419. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31420. var _this = this;
  31421. var localOptions = __assign({ clipPlane: false }, options);
  31422. var subMesh = new BABYLON.BaseSubMesh();
  31423. var scene = this.getScene();
  31424. var checkReady = function () {
  31425. if (!_this._scene || !_this._scene.getEngine()) {
  31426. return;
  31427. }
  31428. if (subMesh._materialDefines) {
  31429. subMesh._materialDefines._renderId = -1;
  31430. }
  31431. var clipPlaneState = scene.clipPlane;
  31432. if (localOptions.clipPlane) {
  31433. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31434. }
  31435. if (_this.storeEffectOnSubMeshes) {
  31436. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31437. if (onCompiled) {
  31438. onCompiled(_this);
  31439. }
  31440. }
  31441. else {
  31442. setTimeout(checkReady, 16);
  31443. }
  31444. }
  31445. else {
  31446. if (_this.isReady(mesh)) {
  31447. if (onCompiled) {
  31448. onCompiled(_this);
  31449. }
  31450. }
  31451. else {
  31452. setTimeout(checkReady, 16);
  31453. }
  31454. }
  31455. if (localOptions.clipPlane) {
  31456. scene.clipPlane = clipPlaneState;
  31457. }
  31458. };
  31459. checkReady();
  31460. };
  31461. /**
  31462. * Force shader compilation.
  31463. * @param mesh The mesh that will use this material
  31464. * @param options Additional options for compiling the shaders
  31465. * @returns A promise that resolves when the compilation completes
  31466. */
  31467. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31468. var _this = this;
  31469. return new Promise(function (resolve) {
  31470. _this.forceCompilation(mesh, function () {
  31471. resolve();
  31472. }, options);
  31473. });
  31474. };
  31475. /**
  31476. * Marks a define in the material to indicate that it needs to be re-computed.
  31477. * @param flag - Material define flag.
  31478. */
  31479. Material.prototype.markAsDirty = function (flag) {
  31480. if (flag & Material.TextureDirtyFlag) {
  31481. this._markAllSubMeshesAsTexturesDirty();
  31482. }
  31483. if (flag & Material.LightDirtyFlag) {
  31484. this._markAllSubMeshesAsLightsDirty();
  31485. }
  31486. if (flag & Material.FresnelDirtyFlag) {
  31487. this._markAllSubMeshesAsFresnelDirty();
  31488. }
  31489. if (flag & Material.AttributesDirtyFlag) {
  31490. this._markAllSubMeshesAsAttributesDirty();
  31491. }
  31492. if (flag & Material.MiscDirtyFlag) {
  31493. this._markAllSubMeshesAsMiscDirty();
  31494. }
  31495. this.getScene().resetCachedMaterial();
  31496. };
  31497. /**
  31498. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31499. * @param func - function which checks material defines against the submeshes.
  31500. */
  31501. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31502. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31503. var mesh = _a[_i];
  31504. if (!mesh.subMeshes) {
  31505. continue;
  31506. }
  31507. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31508. var subMesh = _c[_b];
  31509. if (subMesh.getMaterial() !== this) {
  31510. continue;
  31511. }
  31512. if (!subMesh._materialDefines) {
  31513. continue;
  31514. }
  31515. func(subMesh._materialDefines);
  31516. }
  31517. }
  31518. };
  31519. /**
  31520. * Indicates that image processing needs to be re-calculated for all submeshes.
  31521. */
  31522. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31523. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31524. };
  31525. /**
  31526. * Indicates that textures need to be re-calculated for all submeshes.
  31527. */
  31528. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31529. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31530. };
  31531. /**
  31532. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31533. */
  31534. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31535. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31536. };
  31537. /**
  31538. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31539. */
  31540. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31541. this._markAllSubMeshesAsDirty(function (defines) {
  31542. defines.markAsFresnelDirty();
  31543. defines.markAsMiscDirty();
  31544. });
  31545. };
  31546. /**
  31547. * Indicates that lights need to be re-calculated for all submeshes.
  31548. */
  31549. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31550. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31551. };
  31552. /**
  31553. * Indicates that attributes need to be re-calculated for all submeshes.
  31554. */
  31555. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31556. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31557. };
  31558. /**
  31559. * Indicates that misc needs to be re-calculated for all submeshes.
  31560. */
  31561. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31562. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31563. };
  31564. /**
  31565. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31566. */
  31567. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31568. this._markAllSubMeshesAsDirty(function (defines) {
  31569. defines.markAsTexturesDirty();
  31570. defines.markAsMiscDirty();
  31571. });
  31572. };
  31573. /**
  31574. * Disposes the material.
  31575. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31576. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31577. */
  31578. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31579. // Animations
  31580. this.getScene().stopAnimation(this);
  31581. // Remove from scene
  31582. var index = this._scene.materials.indexOf(this);
  31583. if (index >= 0) {
  31584. this._scene.materials.splice(index, 1);
  31585. }
  31586. // Remove from meshes
  31587. for (index = 0; index < this._scene.meshes.length; index++) {
  31588. var mesh = this._scene.meshes[index];
  31589. if (mesh.material === this) {
  31590. mesh.material = null;
  31591. if (mesh.geometry) {
  31592. var geometry = (mesh.geometry);
  31593. if (this.storeEffectOnSubMeshes) {
  31594. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31595. var subMesh = _a[_i];
  31596. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31597. if (forceDisposeEffect && subMesh._materialEffect) {
  31598. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31599. }
  31600. }
  31601. }
  31602. else {
  31603. geometry._releaseVertexArrayObject(this._effect);
  31604. }
  31605. }
  31606. }
  31607. }
  31608. this._uniformBuffer.dispose();
  31609. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31610. if (forceDisposeEffect && this._effect) {
  31611. if (!this.storeEffectOnSubMeshes) {
  31612. this._scene.getEngine()._releaseEffect(this._effect);
  31613. }
  31614. this._effect = null;
  31615. }
  31616. // Callback
  31617. this.onDisposeObservable.notifyObservers(this);
  31618. this.onDisposeObservable.clear();
  31619. this.onBindObservable.clear();
  31620. this.onUnBindObservable.clear();
  31621. };
  31622. /**
  31623. * Serializes this material.
  31624. * @returns - serialized material object.
  31625. */
  31626. Material.prototype.serialize = function () {
  31627. return BABYLON.SerializationHelper.Serialize(this);
  31628. };
  31629. /**
  31630. * Creates a MultiMaterial from parse MultiMaterial data.
  31631. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31632. * @param scene - BJS scene.
  31633. * @returns - MultiMaterial.
  31634. */
  31635. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31636. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31637. multiMaterial.id = parsedMultiMaterial.id;
  31638. if (BABYLON.Tags) {
  31639. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31640. }
  31641. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31642. var subMatId = parsedMultiMaterial.materials[matIndex];
  31643. if (subMatId) {
  31644. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31645. }
  31646. else {
  31647. multiMaterial.subMaterials.push(null);
  31648. }
  31649. }
  31650. return multiMaterial;
  31651. };
  31652. /**
  31653. * Creates a material from parsed material data.
  31654. * @param parsedMaterial - Parsed material data.
  31655. * @param scene - BJS scene.
  31656. * @param rootUrl - Root URL containing the material information.
  31657. * @returns - Parsed material.
  31658. */
  31659. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31660. if (!parsedMaterial.customType) {
  31661. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31662. }
  31663. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31664. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31665. if (!BABYLON.LegacyPBRMaterial) {
  31666. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31667. return;
  31668. }
  31669. }
  31670. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31671. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31672. ;
  31673. };
  31674. // Triangle views
  31675. Material._TriangleFillMode = 0;
  31676. Material._WireFrameFillMode = 1;
  31677. Material._PointFillMode = 2;
  31678. // Draw modes
  31679. Material._PointListDrawMode = 3;
  31680. Material._LineListDrawMode = 4;
  31681. Material._LineLoopDrawMode = 5;
  31682. Material._LineStripDrawMode = 6;
  31683. Material._TriangleStripDrawMode = 7;
  31684. Material._TriangleFanDrawMode = 8;
  31685. /**
  31686. * Stores the clock-wise side orientation.
  31687. */
  31688. Material._ClockWiseSideOrientation = 0;
  31689. /**
  31690. * Stores the counter clock-wise side orientation.
  31691. */
  31692. Material._CounterClockWiseSideOrientation = 1;
  31693. /**
  31694. * The dirty texture flag value.
  31695. */
  31696. Material._TextureDirtyFlag = 1;
  31697. /**
  31698. * The dirty light flag value.
  31699. */
  31700. Material._LightDirtyFlag = 2;
  31701. /**
  31702. * The dirty fresnel flag value.
  31703. */
  31704. Material._FresnelDirtyFlag = 4;
  31705. /**
  31706. * The dirty attribute flag value.
  31707. */
  31708. Material._AttributesDirtyFlag = 8;
  31709. /**
  31710. * The dirty misc flag value.
  31711. */
  31712. Material._MiscDirtyFlag = 16;
  31713. __decorate([
  31714. BABYLON.serialize()
  31715. ], Material.prototype, "id", void 0);
  31716. __decorate([
  31717. BABYLON.serialize()
  31718. ], Material.prototype, "name", void 0);
  31719. __decorate([
  31720. BABYLON.serialize()
  31721. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31722. __decorate([
  31723. BABYLON.serialize()
  31724. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31725. __decorate([
  31726. BABYLON.serialize()
  31727. ], Material.prototype, "state", void 0);
  31728. __decorate([
  31729. BABYLON.serialize("alpha")
  31730. ], Material.prototype, "_alpha", void 0);
  31731. __decorate([
  31732. BABYLON.serialize("backFaceCulling")
  31733. ], Material.prototype, "_backFaceCulling", void 0);
  31734. __decorate([
  31735. BABYLON.serialize()
  31736. ], Material.prototype, "sideOrientation", void 0);
  31737. __decorate([
  31738. BABYLON.serialize("alphaMode")
  31739. ], Material.prototype, "_alphaMode", void 0);
  31740. __decorate([
  31741. BABYLON.serialize()
  31742. ], Material.prototype, "_needDepthPrePass", void 0);
  31743. __decorate([
  31744. BABYLON.serialize()
  31745. ], Material.prototype, "disableDepthWrite", void 0);
  31746. __decorate([
  31747. BABYLON.serialize()
  31748. ], Material.prototype, "forceDepthWrite", void 0);
  31749. __decorate([
  31750. BABYLON.serialize()
  31751. ], Material.prototype, "separateCullingPass", void 0);
  31752. __decorate([
  31753. BABYLON.serialize("fogEnabled")
  31754. ], Material.prototype, "_fogEnabled", void 0);
  31755. __decorate([
  31756. BABYLON.serialize()
  31757. ], Material.prototype, "pointSize", void 0);
  31758. __decorate([
  31759. BABYLON.serialize()
  31760. ], Material.prototype, "zOffset", void 0);
  31761. __decorate([
  31762. BABYLON.serialize()
  31763. ], Material.prototype, "wireframe", null);
  31764. __decorate([
  31765. BABYLON.serialize()
  31766. ], Material.prototype, "pointsCloud", null);
  31767. __decorate([
  31768. BABYLON.serialize()
  31769. ], Material.prototype, "fillMode", null);
  31770. return Material;
  31771. }());
  31772. BABYLON.Material = Material;
  31773. })(BABYLON || (BABYLON = {}));
  31774. //# sourceMappingURL=babylon.material.js.map
  31775. var BABYLON;
  31776. (function (BABYLON) {
  31777. var UniformBuffer = /** @class */ (function () {
  31778. /**
  31779. * Uniform buffer objects.
  31780. *
  31781. * Handles blocks of uniform on the GPU.
  31782. *
  31783. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31784. *
  31785. * For more information, please refer to :
  31786. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31787. */
  31788. function UniformBuffer(engine, data, dynamic) {
  31789. this._engine = engine;
  31790. this._noUBO = !engine.supportsUniformBuffers;
  31791. this._dynamic = dynamic;
  31792. this._data = data || [];
  31793. this._uniformLocations = {};
  31794. this._uniformSizes = {};
  31795. this._uniformLocationPointer = 0;
  31796. this._needSync = false;
  31797. if (this._noUBO) {
  31798. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31799. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31800. this.updateFloat = this._updateFloatForEffect;
  31801. this.updateFloat2 = this._updateFloat2ForEffect;
  31802. this.updateFloat3 = this._updateFloat3ForEffect;
  31803. this.updateFloat4 = this._updateFloat4ForEffect;
  31804. this.updateMatrix = this._updateMatrixForEffect;
  31805. this.updateVector3 = this._updateVector3ForEffect;
  31806. this.updateVector4 = this._updateVector4ForEffect;
  31807. this.updateColor3 = this._updateColor3ForEffect;
  31808. this.updateColor4 = this._updateColor4ForEffect;
  31809. }
  31810. else {
  31811. this._engine._uniformBuffers.push(this);
  31812. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31813. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31814. this.updateFloat = this._updateFloatForUniform;
  31815. this.updateFloat2 = this._updateFloat2ForUniform;
  31816. this.updateFloat3 = this._updateFloat3ForUniform;
  31817. this.updateFloat4 = this._updateFloat4ForUniform;
  31818. this.updateMatrix = this._updateMatrixForUniform;
  31819. this.updateVector3 = this._updateVector3ForUniform;
  31820. this.updateVector4 = this._updateVector4ForUniform;
  31821. this.updateColor3 = this._updateColor3ForUniform;
  31822. this.updateColor4 = this._updateColor4ForUniform;
  31823. }
  31824. }
  31825. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31826. // Properties
  31827. /**
  31828. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31829. * or just falling back on setUniformXXX calls.
  31830. */
  31831. get: function () {
  31832. return !this._noUBO;
  31833. },
  31834. enumerable: true,
  31835. configurable: true
  31836. });
  31837. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31838. /**
  31839. * Indicates if the WebGL underlying uniform buffer is in sync
  31840. * with the javascript cache data.
  31841. */
  31842. get: function () {
  31843. return !this._needSync;
  31844. },
  31845. enumerable: true,
  31846. configurable: true
  31847. });
  31848. /**
  31849. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31850. * Also, a dynamic UniformBuffer will disable cache verification and always
  31851. * update the underlying WebGL uniform buffer to the GPU.
  31852. */
  31853. UniformBuffer.prototype.isDynamic = function () {
  31854. return this._dynamic !== undefined;
  31855. };
  31856. /**
  31857. * The data cache on JS side.
  31858. */
  31859. UniformBuffer.prototype.getData = function () {
  31860. return this._bufferData;
  31861. };
  31862. /**
  31863. * The underlying WebGL Uniform buffer.
  31864. */
  31865. UniformBuffer.prototype.getBuffer = function () {
  31866. return this._buffer;
  31867. };
  31868. /**
  31869. * std140 layout specifies how to align data within an UBO structure.
  31870. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31871. * for specs.
  31872. */
  31873. UniformBuffer.prototype._fillAlignment = function (size) {
  31874. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31875. // and 4x4 matrices
  31876. // TODO : change if other types are used
  31877. var alignment;
  31878. if (size <= 2) {
  31879. alignment = size;
  31880. }
  31881. else {
  31882. alignment = 4;
  31883. }
  31884. if ((this._uniformLocationPointer % alignment) !== 0) {
  31885. var oldPointer = this._uniformLocationPointer;
  31886. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31887. var diff = this._uniformLocationPointer - oldPointer;
  31888. for (var i = 0; i < diff; i++) {
  31889. this._data.push(0);
  31890. }
  31891. }
  31892. };
  31893. /**
  31894. * Adds an uniform in the buffer.
  31895. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31896. * for the layout to be correct !
  31897. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31898. * @param {number|number[]} size Data size, or data directly.
  31899. */
  31900. UniformBuffer.prototype.addUniform = function (name, size) {
  31901. if (this._noUBO) {
  31902. return;
  31903. }
  31904. if (this._uniformLocations[name] !== undefined) {
  31905. // Already existing uniform
  31906. return;
  31907. }
  31908. // This function must be called in the order of the shader layout !
  31909. // size can be the size of the uniform, or data directly
  31910. var data;
  31911. if (size instanceof Array) {
  31912. data = size;
  31913. size = data.length;
  31914. }
  31915. else {
  31916. size = size;
  31917. data = [];
  31918. // Fill with zeros
  31919. for (var i = 0; i < size; i++) {
  31920. data.push(0);
  31921. }
  31922. }
  31923. this._fillAlignment(size);
  31924. this._uniformSizes[name] = size;
  31925. this._uniformLocations[name] = this._uniformLocationPointer;
  31926. this._uniformLocationPointer += size;
  31927. for (var i = 0; i < size; i++) {
  31928. this._data.push(data[i]);
  31929. }
  31930. this._needSync = true;
  31931. };
  31932. /**
  31933. * Wrapper for addUniform.
  31934. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31935. * @param {Matrix} mat A 4x4 matrix.
  31936. */
  31937. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31938. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31939. };
  31940. /**
  31941. * Wrapper for addUniform.
  31942. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31943. * @param {number} x
  31944. * @param {number} y
  31945. */
  31946. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31947. var temp = [x, y];
  31948. this.addUniform(name, temp);
  31949. };
  31950. /**
  31951. * Wrapper for addUniform.
  31952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31953. * @param {number} x
  31954. * @param {number} y
  31955. * @param {number} z
  31956. */
  31957. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31958. var temp = [x, y, z];
  31959. this.addUniform(name, temp);
  31960. };
  31961. /**
  31962. * Wrapper for addUniform.
  31963. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31964. * @param {Color3} color
  31965. */
  31966. UniformBuffer.prototype.addColor3 = function (name, color) {
  31967. var temp = new Array();
  31968. color.toArray(temp);
  31969. this.addUniform(name, temp);
  31970. };
  31971. /**
  31972. * Wrapper for addUniform.
  31973. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31974. * @param {Color3} color
  31975. * @param {number} alpha
  31976. */
  31977. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31978. var temp = new Array();
  31979. color.toArray(temp);
  31980. temp.push(alpha);
  31981. this.addUniform(name, temp);
  31982. };
  31983. /**
  31984. * Wrapper for addUniform.
  31985. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31986. * @param {Vector3} vector
  31987. */
  31988. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31989. var temp = new Array();
  31990. vector.toArray(temp);
  31991. this.addUniform(name, temp);
  31992. };
  31993. /**
  31994. * Wrapper for addUniform.
  31995. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31996. */
  31997. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31998. this.addUniform(name, 12);
  31999. };
  32000. /**
  32001. * Wrapper for addUniform.
  32002. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32003. */
  32004. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32005. this.addUniform(name, 8);
  32006. };
  32007. /**
  32008. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32009. */
  32010. UniformBuffer.prototype.create = function () {
  32011. if (this._noUBO) {
  32012. return;
  32013. }
  32014. if (this._buffer) {
  32015. return; // nothing to do
  32016. }
  32017. // See spec, alignment must be filled as a vec4
  32018. this._fillAlignment(4);
  32019. this._bufferData = new Float32Array(this._data);
  32020. this._rebuild();
  32021. this._needSync = true;
  32022. };
  32023. UniformBuffer.prototype._rebuild = function () {
  32024. if (this._noUBO) {
  32025. return;
  32026. }
  32027. if (this._dynamic) {
  32028. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32029. }
  32030. else {
  32031. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32032. }
  32033. };
  32034. /**
  32035. * Updates the WebGL Uniform Buffer on the GPU.
  32036. * If the `dynamic` flag is set to true, no cache comparison is done.
  32037. * Otherwise, the buffer will be updated only if the cache differs.
  32038. */
  32039. UniformBuffer.prototype.update = function () {
  32040. if (!this._buffer) {
  32041. this.create();
  32042. return;
  32043. }
  32044. if (!this._dynamic && !this._needSync) {
  32045. return;
  32046. }
  32047. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32048. this._needSync = false;
  32049. };
  32050. /**
  32051. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32052. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32053. * @param {number[]|Float32Array} data Flattened data
  32054. * @param {number} size Size of the data.
  32055. */
  32056. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32057. var location = this._uniformLocations[uniformName];
  32058. if (location === undefined) {
  32059. if (this._buffer) {
  32060. // Cannot add an uniform if the buffer is already created
  32061. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32062. return;
  32063. }
  32064. this.addUniform(uniformName, size);
  32065. location = this._uniformLocations[uniformName];
  32066. }
  32067. if (!this._buffer) {
  32068. this.create();
  32069. }
  32070. if (!this._dynamic) {
  32071. // Cache for static uniform buffers
  32072. var changed = false;
  32073. for (var i = 0; i < size; i++) {
  32074. if (this._bufferData[location + i] !== data[i]) {
  32075. changed = true;
  32076. this._bufferData[location + i] = data[i];
  32077. }
  32078. }
  32079. this._needSync = this._needSync || changed;
  32080. }
  32081. else {
  32082. // No cache for dynamic
  32083. for (var i = 0; i < size; i++) {
  32084. this._bufferData[location + i] = data[i];
  32085. }
  32086. }
  32087. };
  32088. // Update methods
  32089. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32090. // To match std140, matrix must be realigned
  32091. for (var i = 0; i < 3; i++) {
  32092. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32093. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32094. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32095. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32096. }
  32097. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32098. };
  32099. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32100. this._currentEffect.setMatrix3x3(name, matrix);
  32101. };
  32102. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32103. this._currentEffect.setMatrix2x2(name, matrix);
  32104. };
  32105. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32106. // To match std140, matrix must be realigned
  32107. for (var i = 0; i < 2; i++) {
  32108. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32109. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32110. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32111. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32112. }
  32113. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32114. };
  32115. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32116. this._currentEffect.setFloat(name, x);
  32117. };
  32118. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32119. UniformBuffer._tempBuffer[0] = x;
  32120. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32121. };
  32122. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32123. if (suffix === void 0) { suffix = ""; }
  32124. this._currentEffect.setFloat2(name + suffix, x, y);
  32125. };
  32126. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32127. if (suffix === void 0) { suffix = ""; }
  32128. UniformBuffer._tempBuffer[0] = x;
  32129. UniformBuffer._tempBuffer[1] = y;
  32130. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32131. };
  32132. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32133. if (suffix === void 0) { suffix = ""; }
  32134. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32135. };
  32136. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. UniformBuffer._tempBuffer[0] = x;
  32139. UniformBuffer._tempBuffer[1] = y;
  32140. UniformBuffer._tempBuffer[2] = z;
  32141. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32142. };
  32143. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32144. if (suffix === void 0) { suffix = ""; }
  32145. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32146. };
  32147. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32148. if (suffix === void 0) { suffix = ""; }
  32149. UniformBuffer._tempBuffer[0] = x;
  32150. UniformBuffer._tempBuffer[1] = y;
  32151. UniformBuffer._tempBuffer[2] = z;
  32152. UniformBuffer._tempBuffer[3] = w;
  32153. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32154. };
  32155. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32156. this._currentEffect.setMatrix(name, mat);
  32157. };
  32158. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32159. this.updateUniform(name, mat.toArray(), 16);
  32160. };
  32161. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32162. this._currentEffect.setVector3(name, vector);
  32163. };
  32164. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32165. vector.toArray(UniformBuffer._tempBuffer);
  32166. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32167. };
  32168. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32169. this._currentEffect.setVector4(name, vector);
  32170. };
  32171. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32172. vector.toArray(UniformBuffer._tempBuffer);
  32173. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32174. };
  32175. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32176. if (suffix === void 0) { suffix = ""; }
  32177. this._currentEffect.setColor3(name + suffix, color);
  32178. };
  32179. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32180. if (suffix === void 0) { suffix = ""; }
  32181. color.toArray(UniformBuffer._tempBuffer);
  32182. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32183. };
  32184. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32185. if (suffix === void 0) { suffix = ""; }
  32186. this._currentEffect.setColor4(name + suffix, color, alpha);
  32187. };
  32188. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32189. if (suffix === void 0) { suffix = ""; }
  32190. color.toArray(UniformBuffer._tempBuffer);
  32191. UniformBuffer._tempBuffer[3] = alpha;
  32192. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32193. };
  32194. /**
  32195. * Sets a sampler uniform on the effect.
  32196. * @param {string} name Name of the sampler.
  32197. * @param {Texture} texture
  32198. */
  32199. UniformBuffer.prototype.setTexture = function (name, texture) {
  32200. this._currentEffect.setTexture(name, texture);
  32201. };
  32202. /**
  32203. * Directly updates the value of the uniform in the cache AND on the GPU.
  32204. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32205. * @param {number[]|Float32Array} data Flattened data
  32206. */
  32207. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32208. this.updateUniform(uniformName, data, data.length);
  32209. this.update();
  32210. };
  32211. /**
  32212. * Binds this uniform buffer to an effect.
  32213. * @param {Effect} effect
  32214. * @param {string} name Name of the uniform block in the shader.
  32215. */
  32216. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32217. this._currentEffect = effect;
  32218. if (this._noUBO || !this._buffer) {
  32219. return;
  32220. }
  32221. effect.bindUniformBuffer(this._buffer, name);
  32222. };
  32223. /**
  32224. * Disposes the uniform buffer.
  32225. */
  32226. UniformBuffer.prototype.dispose = function () {
  32227. if (this._noUBO) {
  32228. return;
  32229. }
  32230. var index = this._engine._uniformBuffers.indexOf(this);
  32231. if (index !== -1) {
  32232. this._engine._uniformBuffers.splice(index, 1);
  32233. }
  32234. if (!this._buffer) {
  32235. return;
  32236. }
  32237. if (this._engine._releaseBuffer(this._buffer)) {
  32238. this._buffer = null;
  32239. }
  32240. };
  32241. // Pool for avoiding memory leaks
  32242. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32243. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32244. return UniformBuffer;
  32245. }());
  32246. BABYLON.UniformBuffer = UniformBuffer;
  32247. })(BABYLON || (BABYLON = {}));
  32248. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32249. var BABYLON;
  32250. (function (BABYLON) {
  32251. var VertexData = /** @class */ (function () {
  32252. function VertexData() {
  32253. }
  32254. VertexData.prototype.set = function (data, kind) {
  32255. switch (kind) {
  32256. case BABYLON.VertexBuffer.PositionKind:
  32257. this.positions = data;
  32258. break;
  32259. case BABYLON.VertexBuffer.NormalKind:
  32260. this.normals = data;
  32261. break;
  32262. case BABYLON.VertexBuffer.TangentKind:
  32263. this.tangents = data;
  32264. break;
  32265. case BABYLON.VertexBuffer.UVKind:
  32266. this.uvs = data;
  32267. break;
  32268. case BABYLON.VertexBuffer.UV2Kind:
  32269. this.uvs2 = data;
  32270. break;
  32271. case BABYLON.VertexBuffer.UV3Kind:
  32272. this.uvs3 = data;
  32273. break;
  32274. case BABYLON.VertexBuffer.UV4Kind:
  32275. this.uvs4 = data;
  32276. break;
  32277. case BABYLON.VertexBuffer.UV5Kind:
  32278. this.uvs5 = data;
  32279. break;
  32280. case BABYLON.VertexBuffer.UV6Kind:
  32281. this.uvs6 = data;
  32282. break;
  32283. case BABYLON.VertexBuffer.ColorKind:
  32284. this.colors = data;
  32285. break;
  32286. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32287. this.matricesIndices = data;
  32288. break;
  32289. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32290. this.matricesWeights = data;
  32291. break;
  32292. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32293. this.matricesIndicesExtra = data;
  32294. break;
  32295. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32296. this.matricesWeightsExtra = data;
  32297. break;
  32298. }
  32299. };
  32300. /**
  32301. * Associates the vertexData to the passed Mesh.
  32302. * Sets it as updatable or not (default `false`).
  32303. * Returns the VertexData.
  32304. */
  32305. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32306. this._applyTo(mesh, updatable);
  32307. return this;
  32308. };
  32309. /**
  32310. * Associates the vertexData to the passed Geometry.
  32311. * Sets it as updatable or not (default `false`).
  32312. * Returns the VertexData.
  32313. */
  32314. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32315. this._applyTo(geometry, updatable);
  32316. return this;
  32317. };
  32318. /**
  32319. * Updates the associated mesh.
  32320. * Returns the VertexData.
  32321. */
  32322. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32323. this._update(mesh);
  32324. return this;
  32325. };
  32326. /**
  32327. * Updates the associated geometry.
  32328. * Returns the VertexData.
  32329. */
  32330. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32331. this._update(geometry);
  32332. return this;
  32333. };
  32334. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32335. if (updatable === void 0) { updatable = false; }
  32336. if (this.positions) {
  32337. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32338. }
  32339. if (this.normals) {
  32340. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32341. }
  32342. if (this.tangents) {
  32343. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32344. }
  32345. if (this.uvs) {
  32346. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32347. }
  32348. if (this.uvs2) {
  32349. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32350. }
  32351. if (this.uvs3) {
  32352. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32353. }
  32354. if (this.uvs4) {
  32355. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32356. }
  32357. if (this.uvs5) {
  32358. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32359. }
  32360. if (this.uvs6) {
  32361. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32362. }
  32363. if (this.colors) {
  32364. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32365. }
  32366. if (this.matricesIndices) {
  32367. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32368. }
  32369. if (this.matricesWeights) {
  32370. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32371. }
  32372. if (this.matricesIndicesExtra) {
  32373. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32374. }
  32375. if (this.matricesWeightsExtra) {
  32376. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32377. }
  32378. if (this.indices) {
  32379. meshOrGeometry.setIndices(this.indices, null, updatable);
  32380. }
  32381. return this;
  32382. };
  32383. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32384. if (this.positions) {
  32385. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32386. }
  32387. if (this.normals) {
  32388. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32389. }
  32390. if (this.tangents) {
  32391. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32392. }
  32393. if (this.uvs) {
  32394. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32395. }
  32396. if (this.uvs2) {
  32397. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32398. }
  32399. if (this.uvs3) {
  32400. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32401. }
  32402. if (this.uvs4) {
  32403. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32404. }
  32405. if (this.uvs5) {
  32406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32407. }
  32408. if (this.uvs6) {
  32409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32410. }
  32411. if (this.colors) {
  32412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32413. }
  32414. if (this.matricesIndices) {
  32415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32416. }
  32417. if (this.matricesWeights) {
  32418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32419. }
  32420. if (this.matricesIndicesExtra) {
  32421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32422. }
  32423. if (this.matricesWeightsExtra) {
  32424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32425. }
  32426. if (this.indices) {
  32427. meshOrGeometry.setIndices(this.indices, null);
  32428. }
  32429. return this;
  32430. };
  32431. /**
  32432. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32433. * Returns the VertexData.
  32434. */
  32435. VertexData.prototype.transform = function (matrix) {
  32436. var transformed = BABYLON.Vector3.Zero();
  32437. var index;
  32438. if (this.positions) {
  32439. var position = BABYLON.Vector3.Zero();
  32440. for (index = 0; index < this.positions.length; index += 3) {
  32441. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32442. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32443. this.positions[index] = transformed.x;
  32444. this.positions[index + 1] = transformed.y;
  32445. this.positions[index + 2] = transformed.z;
  32446. }
  32447. }
  32448. if (this.normals) {
  32449. var normal = BABYLON.Vector3.Zero();
  32450. for (index = 0; index < this.normals.length; index += 3) {
  32451. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32452. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32453. this.normals[index] = transformed.x;
  32454. this.normals[index + 1] = transformed.y;
  32455. this.normals[index + 2] = transformed.z;
  32456. }
  32457. }
  32458. if (this.tangents) {
  32459. var tangent = BABYLON.Vector4.Zero();
  32460. var tangentTransformed = BABYLON.Vector4.Zero();
  32461. for (index = 0; index < this.tangents.length; index += 4) {
  32462. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32463. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32464. this.tangents[index] = tangentTransformed.x;
  32465. this.tangents[index + 1] = tangentTransformed.y;
  32466. this.tangents[index + 2] = tangentTransformed.z;
  32467. this.tangents[index + 3] = tangentTransformed.w;
  32468. }
  32469. }
  32470. return this;
  32471. };
  32472. /**
  32473. * Merges the passed VertexData into the current one.
  32474. * Returns the modified VertexData.
  32475. */
  32476. VertexData.prototype.merge = function (other) {
  32477. this._validate();
  32478. other._validate();
  32479. if (!this.normals !== !other.normals ||
  32480. !this.tangents !== !other.tangents ||
  32481. !this.uvs !== !other.uvs ||
  32482. !this.uvs2 !== !other.uvs2 ||
  32483. !this.uvs3 !== !other.uvs3 ||
  32484. !this.uvs4 !== !other.uvs4 ||
  32485. !this.uvs5 !== !other.uvs5 ||
  32486. !this.uvs6 !== !other.uvs6 ||
  32487. !this.colors !== !other.colors ||
  32488. !this.matricesIndices !== !other.matricesIndices ||
  32489. !this.matricesWeights !== !other.matricesWeights ||
  32490. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32491. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32492. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32493. }
  32494. if (other.indices) {
  32495. if (!this.indices) {
  32496. this.indices = [];
  32497. }
  32498. var offset = this.positions ? this.positions.length / 3 : 0;
  32499. for (var index = 0; index < other.indices.length; index++) {
  32500. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32501. this.indices.push(other.indices[index] + offset);
  32502. }
  32503. }
  32504. this.positions = this._mergeElement(this.positions, other.positions);
  32505. this.normals = this._mergeElement(this.normals, other.normals);
  32506. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32507. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32508. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32509. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32510. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32511. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32512. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32513. this.colors = this._mergeElement(this.colors, other.colors);
  32514. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32515. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32516. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32517. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32518. return this;
  32519. };
  32520. VertexData.prototype._mergeElement = function (source, other) {
  32521. if (!source) {
  32522. return other;
  32523. }
  32524. if (!other) {
  32525. return source;
  32526. }
  32527. var len = other.length + source.length;
  32528. var isSrcTypedArray = source instanceof Float32Array;
  32529. var isOthTypedArray = other instanceof Float32Array;
  32530. // use non-loop method when the source is Float32Array
  32531. if (isSrcTypedArray) {
  32532. var ret32 = new Float32Array(len);
  32533. ret32.set(source);
  32534. ret32.set(other, source.length);
  32535. return ret32;
  32536. // source is number[], when other is also use concat
  32537. }
  32538. else if (!isOthTypedArray) {
  32539. return source.concat(other);
  32540. // source is a number[], but other is a Float32Array, loop required
  32541. }
  32542. else {
  32543. var ret = source.slice(0); // copy source to a separate array
  32544. for (var i = 0, len = other.length; i < len; i++) {
  32545. ret.push(other[i]);
  32546. }
  32547. return ret;
  32548. }
  32549. };
  32550. VertexData.prototype._validate = function () {
  32551. if (!this.positions) {
  32552. throw new Error("Positions are required");
  32553. }
  32554. var getElementCount = function (kind, values) {
  32555. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32556. if ((values.length % stride) !== 0) {
  32557. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32558. }
  32559. return values.length / stride;
  32560. };
  32561. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32562. var validateElementCount = function (kind, values) {
  32563. var elementCount = getElementCount(kind, values);
  32564. if (elementCount !== positionsElementCount) {
  32565. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32566. }
  32567. };
  32568. if (this.normals)
  32569. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32570. if (this.tangents)
  32571. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32572. if (this.uvs)
  32573. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32574. if (this.uvs2)
  32575. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32576. if (this.uvs3)
  32577. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32578. if (this.uvs4)
  32579. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32580. if (this.uvs5)
  32581. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32582. if (this.uvs6)
  32583. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32584. if (this.colors)
  32585. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32586. if (this.matricesIndices)
  32587. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32588. if (this.matricesWeights)
  32589. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32590. if (this.matricesIndicesExtra)
  32591. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32592. if (this.matricesWeightsExtra)
  32593. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32594. };
  32595. /**
  32596. * Serializes the VertexData.
  32597. * Returns a serialized object.
  32598. */
  32599. VertexData.prototype.serialize = function () {
  32600. var serializationObject = this.serialize();
  32601. if (this.positions) {
  32602. serializationObject.positions = this.positions;
  32603. }
  32604. if (this.normals) {
  32605. serializationObject.normals = this.normals;
  32606. }
  32607. if (this.tangents) {
  32608. serializationObject.tangents = this.tangents;
  32609. }
  32610. if (this.uvs) {
  32611. serializationObject.uvs = this.uvs;
  32612. }
  32613. if (this.uvs2) {
  32614. serializationObject.uvs2 = this.uvs2;
  32615. }
  32616. if (this.uvs3) {
  32617. serializationObject.uvs3 = this.uvs3;
  32618. }
  32619. if (this.uvs4) {
  32620. serializationObject.uvs4 = this.uvs4;
  32621. }
  32622. if (this.uvs5) {
  32623. serializationObject.uvs5 = this.uvs5;
  32624. }
  32625. if (this.uvs6) {
  32626. serializationObject.uvs6 = this.uvs6;
  32627. }
  32628. if (this.colors) {
  32629. serializationObject.colors = this.colors;
  32630. }
  32631. if (this.matricesIndices) {
  32632. serializationObject.matricesIndices = this.matricesIndices;
  32633. serializationObject.matricesIndices._isExpanded = true;
  32634. }
  32635. if (this.matricesWeights) {
  32636. serializationObject.matricesWeights = this.matricesWeights;
  32637. }
  32638. if (this.matricesIndicesExtra) {
  32639. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32640. serializationObject.matricesIndicesExtra._isExpanded = true;
  32641. }
  32642. if (this.matricesWeightsExtra) {
  32643. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32644. }
  32645. serializationObject.indices = this.indices;
  32646. return serializationObject;
  32647. };
  32648. // Statics
  32649. /**
  32650. * Returns the object VertexData associated to the passed mesh.
  32651. */
  32652. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32653. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32654. };
  32655. /**
  32656. * Returns the object VertexData associated to the passed geometry.
  32657. */
  32658. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32659. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32660. };
  32661. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32662. var result = new VertexData();
  32663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32664. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32665. }
  32666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32667. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32668. }
  32669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32670. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32671. }
  32672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32673. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32674. }
  32675. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32676. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32677. }
  32678. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32679. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32680. }
  32681. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32682. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32683. }
  32684. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32685. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32686. }
  32687. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32688. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32689. }
  32690. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32691. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32692. }
  32693. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32694. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32695. }
  32696. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32697. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32698. }
  32699. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32700. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32701. }
  32702. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32703. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32704. }
  32705. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32706. return result;
  32707. };
  32708. /**
  32709. * Creates the vertexData of the Ribbon.
  32710. */
  32711. VertexData.CreateRibbon = function (options) {
  32712. var pathArray = options.pathArray;
  32713. var closeArray = options.closeArray || false;
  32714. var closePath = options.closePath || false;
  32715. var invertUV = options.invertUV || false;
  32716. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32717. var offset = options.offset || defaultOffset;
  32718. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32719. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32720. var customUV = options.uvs;
  32721. var customColors = options.colors;
  32722. var positions = [];
  32723. var indices = [];
  32724. var normals = [];
  32725. var uvs = [];
  32726. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32727. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32728. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32729. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32730. var minlg; // minimal length among all paths from pathArray
  32731. var lg = []; // array of path lengths : nb of vertex per path
  32732. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32733. var p; // path iterator
  32734. var i; // point iterator
  32735. var j; // point iterator
  32736. // if single path in pathArray
  32737. if (pathArray.length < 2) {
  32738. var ar1 = [];
  32739. var ar2 = [];
  32740. for (i = 0; i < pathArray[0].length - offset; i++) {
  32741. ar1.push(pathArray[0][i]);
  32742. ar2.push(pathArray[0][i + offset]);
  32743. }
  32744. pathArray = [ar1, ar2];
  32745. }
  32746. // positions and horizontal distances (u)
  32747. var idc = 0;
  32748. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32749. var path;
  32750. var l;
  32751. minlg = pathArray[0].length;
  32752. var vectlg;
  32753. var dist;
  32754. for (p = 0; p < pathArray.length; p++) {
  32755. uTotalDistance[p] = 0;
  32756. us[p] = [0];
  32757. path = pathArray[p];
  32758. l = path.length;
  32759. minlg = (minlg < l) ? minlg : l;
  32760. j = 0;
  32761. while (j < l) {
  32762. positions.push(path[j].x, path[j].y, path[j].z);
  32763. if (j > 0) {
  32764. vectlg = path[j].subtract(path[j - 1]).length();
  32765. dist = vectlg + uTotalDistance[p];
  32766. us[p].push(dist);
  32767. uTotalDistance[p] = dist;
  32768. }
  32769. j++;
  32770. }
  32771. if (closePath) {
  32772. j--;
  32773. positions.push(path[0].x, path[0].y, path[0].z);
  32774. vectlg = path[j].subtract(path[0]).length();
  32775. dist = vectlg + uTotalDistance[p];
  32776. us[p].push(dist);
  32777. uTotalDistance[p] = dist;
  32778. }
  32779. lg[p] = l + closePathCorr;
  32780. idx[p] = idc;
  32781. idc += (l + closePathCorr);
  32782. }
  32783. // vertical distances (v)
  32784. var path1;
  32785. var path2;
  32786. var vertex1 = null;
  32787. var vertex2 = null;
  32788. for (i = 0; i < minlg + closePathCorr; i++) {
  32789. vTotalDistance[i] = 0;
  32790. vs[i] = [0];
  32791. for (p = 0; p < pathArray.length - 1; p++) {
  32792. path1 = pathArray[p];
  32793. path2 = pathArray[p + 1];
  32794. if (i === minlg) {
  32795. vertex1 = path1[0];
  32796. vertex2 = path2[0];
  32797. }
  32798. else {
  32799. vertex1 = path1[i];
  32800. vertex2 = path2[i];
  32801. }
  32802. vectlg = vertex2.subtract(vertex1).length();
  32803. dist = vectlg + vTotalDistance[i];
  32804. vs[i].push(dist);
  32805. vTotalDistance[i] = dist;
  32806. }
  32807. if (closeArray && vertex2 && vertex1) {
  32808. path1 = pathArray[p];
  32809. path2 = pathArray[0];
  32810. if (i === minlg) {
  32811. vertex2 = path2[0];
  32812. }
  32813. vectlg = vertex2.subtract(vertex1).length();
  32814. dist = vectlg + vTotalDistance[i];
  32815. vTotalDistance[i] = dist;
  32816. }
  32817. }
  32818. // uvs
  32819. var u;
  32820. var v;
  32821. if (customUV) {
  32822. for (p = 0; p < customUV.length; p++) {
  32823. uvs.push(customUV[p].x, customUV[p].y);
  32824. }
  32825. }
  32826. else {
  32827. for (p = 0; p < pathArray.length; p++) {
  32828. for (i = 0; i < minlg + closePathCorr; i++) {
  32829. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32830. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32831. if (invertUV) {
  32832. uvs.push(v, u);
  32833. }
  32834. else {
  32835. uvs.push(u, v);
  32836. }
  32837. }
  32838. }
  32839. }
  32840. // indices
  32841. p = 0; // path index
  32842. var pi = 0; // positions array index
  32843. var l1 = lg[p] - 1; // path1 length
  32844. var l2 = lg[p + 1] - 1; // path2 length
  32845. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32846. var shft = idx[1] - idx[0]; // shift
  32847. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32848. while (pi <= min && p < path1nb) {
  32849. // 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
  32850. indices.push(pi, pi + shft, pi + 1);
  32851. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32852. pi += 1;
  32853. if (pi === min) {
  32854. p++;
  32855. if (p === lg.length - 1) {
  32856. shft = idx[0] - idx[p];
  32857. l1 = lg[p] - 1;
  32858. l2 = lg[0] - 1;
  32859. }
  32860. else {
  32861. shft = idx[p + 1] - idx[p];
  32862. l1 = lg[p] - 1;
  32863. l2 = lg[p + 1] - 1;
  32864. }
  32865. pi = idx[p];
  32866. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32867. }
  32868. }
  32869. // normals
  32870. VertexData.ComputeNormals(positions, indices, normals);
  32871. if (closePath) {
  32872. var indexFirst = 0;
  32873. var indexLast = 0;
  32874. for (p = 0; p < pathArray.length; p++) {
  32875. indexFirst = idx[p] * 3;
  32876. if (p + 1 < pathArray.length) {
  32877. indexLast = (idx[p + 1] - 1) * 3;
  32878. }
  32879. else {
  32880. indexLast = normals.length - 3;
  32881. }
  32882. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32883. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32884. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32885. normals[indexLast] = normals[indexFirst];
  32886. normals[indexLast + 1] = normals[indexFirst + 1];
  32887. normals[indexLast + 2] = normals[indexFirst + 2];
  32888. }
  32889. }
  32890. // sides
  32891. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32892. // Colors
  32893. var colors = null;
  32894. if (customColors) {
  32895. colors = new Float32Array(customColors.length * 4);
  32896. for (var c = 0; c < customColors.length; c++) {
  32897. colors[c * 4] = customColors[c].r;
  32898. colors[c * 4 + 1] = customColors[c].g;
  32899. colors[c * 4 + 2] = customColors[c].b;
  32900. colors[c * 4 + 3] = customColors[c].a;
  32901. }
  32902. }
  32903. // Result
  32904. var vertexData = new VertexData();
  32905. var positions32 = new Float32Array(positions);
  32906. var normals32 = new Float32Array(normals);
  32907. var uvs32 = new Float32Array(uvs);
  32908. vertexData.indices = indices;
  32909. vertexData.positions = positions32;
  32910. vertexData.normals = normals32;
  32911. vertexData.uvs = uvs32;
  32912. if (colors) {
  32913. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32914. }
  32915. if (closePath) {
  32916. vertexData._idx = idx;
  32917. }
  32918. return vertexData;
  32919. };
  32920. /**
  32921. * Creates the VertexData of the Box.
  32922. */
  32923. VertexData.CreateBox = function (options) {
  32924. var normalsSource = [
  32925. new BABYLON.Vector3(0, 0, 1),
  32926. new BABYLON.Vector3(0, 0, -1),
  32927. new BABYLON.Vector3(1, 0, 0),
  32928. new BABYLON.Vector3(-1, 0, 0),
  32929. new BABYLON.Vector3(0, 1, 0),
  32930. new BABYLON.Vector3(0, -1, 0)
  32931. ];
  32932. var indices = [];
  32933. var positions = [];
  32934. var normals = [];
  32935. var uvs = [];
  32936. var width = options.width || options.size || 1;
  32937. var height = options.height || options.size || 1;
  32938. var depth = options.depth || options.size || 1;
  32939. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32940. var faceUV = options.faceUV || new Array(6);
  32941. var faceColors = options.faceColors;
  32942. var colors = [];
  32943. // default face colors and UV if undefined
  32944. for (var f = 0; f < 6; f++) {
  32945. if (faceUV[f] === undefined) {
  32946. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32947. }
  32948. if (faceColors && faceColors[f] === undefined) {
  32949. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32950. }
  32951. }
  32952. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32953. // Create each face in turn.
  32954. for (var index = 0; index < normalsSource.length; index++) {
  32955. var normal = normalsSource[index];
  32956. // Get two vectors perpendicular to the face normal and to each other.
  32957. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32958. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32959. // Six indices (two triangles) per face.
  32960. var verticesLength = positions.length / 3;
  32961. indices.push(verticesLength);
  32962. indices.push(verticesLength + 1);
  32963. indices.push(verticesLength + 2);
  32964. indices.push(verticesLength);
  32965. indices.push(verticesLength + 2);
  32966. indices.push(verticesLength + 3);
  32967. // Four vertices per face.
  32968. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32969. positions.push(vertex.x, vertex.y, vertex.z);
  32970. normals.push(normal.x, normal.y, normal.z);
  32971. uvs.push(faceUV[index].z, faceUV[index].w);
  32972. if (faceColors) {
  32973. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32974. }
  32975. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32976. positions.push(vertex.x, vertex.y, vertex.z);
  32977. normals.push(normal.x, normal.y, normal.z);
  32978. uvs.push(faceUV[index].x, faceUV[index].w);
  32979. if (faceColors) {
  32980. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32981. }
  32982. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32983. positions.push(vertex.x, vertex.y, vertex.z);
  32984. normals.push(normal.x, normal.y, normal.z);
  32985. uvs.push(faceUV[index].x, faceUV[index].y);
  32986. if (faceColors) {
  32987. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32988. }
  32989. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32990. positions.push(vertex.x, vertex.y, vertex.z);
  32991. normals.push(normal.x, normal.y, normal.z);
  32992. uvs.push(faceUV[index].z, faceUV[index].y);
  32993. if (faceColors) {
  32994. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32995. }
  32996. }
  32997. // sides
  32998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32999. // Result
  33000. var vertexData = new VertexData();
  33001. vertexData.indices = indices;
  33002. vertexData.positions = positions;
  33003. vertexData.normals = normals;
  33004. vertexData.uvs = uvs;
  33005. if (faceColors) {
  33006. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33007. vertexData.colors = totalColors;
  33008. }
  33009. return vertexData;
  33010. };
  33011. /**
  33012. * Creates the VertexData of the Sphere.
  33013. */
  33014. VertexData.CreateSphere = function (options) {
  33015. var segments = options.segments || 32;
  33016. var diameterX = options.diameterX || options.diameter || 1;
  33017. var diameterY = options.diameterY || options.diameter || 1;
  33018. var diameterZ = options.diameterZ || options.diameter || 1;
  33019. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33020. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33022. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33023. var totalZRotationSteps = 2 + segments;
  33024. var totalYRotationSteps = 2 * totalZRotationSteps;
  33025. var indices = [];
  33026. var positions = [];
  33027. var normals = [];
  33028. var uvs = [];
  33029. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33030. var normalizedZ = zRotationStep / totalZRotationSteps;
  33031. var angleZ = normalizedZ * Math.PI * slice;
  33032. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33033. var normalizedY = yRotationStep / totalYRotationSteps;
  33034. var angleY = normalizedY * Math.PI * 2 * arc;
  33035. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33036. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33037. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33038. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33039. var vertex = complete.multiply(radius);
  33040. var normal = complete.divide(radius).normalize();
  33041. positions.push(vertex.x, vertex.y, vertex.z);
  33042. normals.push(normal.x, normal.y, normal.z);
  33043. uvs.push(normalizedY, normalizedZ);
  33044. }
  33045. if (zRotationStep > 0) {
  33046. var verticesCount = positions.length / 3;
  33047. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33048. indices.push((firstIndex));
  33049. indices.push((firstIndex + 1));
  33050. indices.push(firstIndex + totalYRotationSteps + 1);
  33051. indices.push((firstIndex + totalYRotationSteps + 1));
  33052. indices.push((firstIndex + 1));
  33053. indices.push((firstIndex + totalYRotationSteps + 2));
  33054. }
  33055. }
  33056. }
  33057. // Sides
  33058. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33059. // Result
  33060. var vertexData = new VertexData();
  33061. vertexData.indices = indices;
  33062. vertexData.positions = positions;
  33063. vertexData.normals = normals;
  33064. vertexData.uvs = uvs;
  33065. return vertexData;
  33066. };
  33067. /**
  33068. * Creates the VertexData of the Cylinder or Cone.
  33069. */
  33070. VertexData.CreateCylinder = function (options) {
  33071. var height = options.height || 2;
  33072. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33073. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33074. var tessellation = options.tessellation || 24;
  33075. var subdivisions = options.subdivisions || 1;
  33076. var hasRings = options.hasRings ? true : false;
  33077. var enclose = options.enclose ? true : false;
  33078. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33080. var faceUV = options.faceUV || new Array(3);
  33081. var faceColors = options.faceColors;
  33082. // default face colors and UV if undefined
  33083. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33084. var ringNb = (hasRings) ? subdivisions : 1;
  33085. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33086. var f;
  33087. for (f = 0; f < surfaceNb; f++) {
  33088. if (faceColors && faceColors[f] === undefined) {
  33089. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33090. }
  33091. }
  33092. for (f = 0; f < surfaceNb; f++) {
  33093. if (faceUV && faceUV[f] === undefined) {
  33094. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33095. }
  33096. }
  33097. var indices = new Array();
  33098. var positions = new Array();
  33099. var normals = new Array();
  33100. var uvs = new Array();
  33101. var colors = new Array();
  33102. var angle_step = Math.PI * 2 * arc / tessellation;
  33103. var angle;
  33104. var h;
  33105. var radius;
  33106. var tan = (diameterBottom - diameterTop) / 2 / height;
  33107. var ringVertex = BABYLON.Vector3.Zero();
  33108. var ringNormal = BABYLON.Vector3.Zero();
  33109. var ringFirstVertex = BABYLON.Vector3.Zero();
  33110. var ringFirstNormal = BABYLON.Vector3.Zero();
  33111. var quadNormal = BABYLON.Vector3.Zero();
  33112. var Y = BABYLON.Axis.Y;
  33113. // positions, normals, uvs
  33114. var i;
  33115. var j;
  33116. var r;
  33117. var ringIdx = 1;
  33118. var s = 1; // surface index
  33119. var cs = 0;
  33120. var v = 0;
  33121. for (i = 0; i <= subdivisions; i++) {
  33122. h = i / subdivisions;
  33123. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33124. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33125. for (r = 0; r < ringIdx; r++) {
  33126. if (hasRings) {
  33127. s += r;
  33128. }
  33129. if (enclose) {
  33130. s += 2 * r;
  33131. }
  33132. for (j = 0; j <= tessellation; j++) {
  33133. angle = j * angle_step;
  33134. // position
  33135. ringVertex.x = Math.cos(-angle) * radius;
  33136. ringVertex.y = -height / 2 + h * height;
  33137. ringVertex.z = Math.sin(-angle) * radius;
  33138. // normal
  33139. if (diameterTop === 0 && i === subdivisions) {
  33140. // if no top cap, reuse former normals
  33141. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33142. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33143. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33144. }
  33145. else {
  33146. ringNormal.x = ringVertex.x;
  33147. ringNormal.z = ringVertex.z;
  33148. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33149. ringNormal.normalize();
  33150. }
  33151. // keep first ring vertex values for enclose
  33152. if (j === 0) {
  33153. ringFirstVertex.copyFrom(ringVertex);
  33154. ringFirstNormal.copyFrom(ringNormal);
  33155. }
  33156. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33157. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33158. if (hasRings) {
  33159. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33160. }
  33161. else {
  33162. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33163. }
  33164. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33165. if (faceColors) {
  33166. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33167. }
  33168. }
  33169. // if enclose, add four vertices and their dedicated normals
  33170. if (arc !== 1 && enclose) {
  33171. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33172. positions.push(0, ringVertex.y, 0);
  33173. positions.push(0, ringVertex.y, 0);
  33174. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33175. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33176. quadNormal.normalize();
  33177. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33178. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33179. quadNormal.normalize();
  33180. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33181. if (hasRings) {
  33182. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33183. }
  33184. else {
  33185. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33186. }
  33187. uvs.push(faceUV[s + 1].x, v);
  33188. uvs.push(faceUV[s + 1].z, v);
  33189. if (hasRings) {
  33190. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33191. }
  33192. else {
  33193. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33194. }
  33195. uvs.push(faceUV[s + 2].x, v);
  33196. uvs.push(faceUV[s + 2].z, v);
  33197. if (faceColors) {
  33198. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33199. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33200. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33201. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33202. }
  33203. }
  33204. if (cs !== s) {
  33205. cs = s;
  33206. }
  33207. }
  33208. }
  33209. // indices
  33210. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33211. var s;
  33212. i = 0;
  33213. for (s = 0; s < subdivisions; s++) {
  33214. var i0 = 0;
  33215. var i1 = 0;
  33216. var i2 = 0;
  33217. var i3 = 0;
  33218. for (j = 0; j < tessellation; j++) {
  33219. i0 = i * (e + 1) + j;
  33220. i1 = (i + 1) * (e + 1) + j;
  33221. i2 = i * (e + 1) + (j + 1);
  33222. i3 = (i + 1) * (e + 1) + (j + 1);
  33223. indices.push(i0, i1, i2);
  33224. indices.push(i3, i2, i1);
  33225. }
  33226. if (arc !== 1 && enclose) {
  33227. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33228. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33229. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33230. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33231. }
  33232. i = (hasRings) ? (i + 2) : (i + 1);
  33233. }
  33234. // Caps
  33235. var createCylinderCap = function (isTop) {
  33236. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33237. if (radius === 0) {
  33238. return;
  33239. }
  33240. // Cap positions, normals & uvs
  33241. var angle;
  33242. var circleVector;
  33243. var i;
  33244. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33245. var c = null;
  33246. if (faceColors) {
  33247. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33248. }
  33249. // cap center
  33250. var vbase = positions.length / 3;
  33251. var offset = isTop ? height / 2 : -height / 2;
  33252. var center = new BABYLON.Vector3(0, offset, 0);
  33253. positions.push(center.x, center.y, center.z);
  33254. normals.push(0, isTop ? 1 : -1, 0);
  33255. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33256. if (c) {
  33257. colors.push(c.r, c.g, c.b, c.a);
  33258. }
  33259. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33260. for (i = 0; i <= tessellation; i++) {
  33261. angle = Math.PI * 2 * i * arc / tessellation;
  33262. var cos = Math.cos(-angle);
  33263. var sin = Math.sin(-angle);
  33264. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33265. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33266. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33267. normals.push(0, isTop ? 1 : -1, 0);
  33268. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33269. if (c) {
  33270. colors.push(c.r, c.g, c.b, c.a);
  33271. }
  33272. }
  33273. // Cap indices
  33274. for (i = 0; i < tessellation; i++) {
  33275. if (!isTop) {
  33276. indices.push(vbase);
  33277. indices.push(vbase + (i + 1));
  33278. indices.push(vbase + (i + 2));
  33279. }
  33280. else {
  33281. indices.push(vbase);
  33282. indices.push(vbase + (i + 2));
  33283. indices.push(vbase + (i + 1));
  33284. }
  33285. }
  33286. };
  33287. // add caps to geometry
  33288. createCylinderCap(false);
  33289. createCylinderCap(true);
  33290. // Sides
  33291. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33292. var vertexData = new VertexData();
  33293. vertexData.indices = indices;
  33294. vertexData.positions = positions;
  33295. vertexData.normals = normals;
  33296. vertexData.uvs = uvs;
  33297. if (faceColors) {
  33298. vertexData.colors = colors;
  33299. }
  33300. return vertexData;
  33301. };
  33302. /**
  33303. * Creates the VertexData of the Torus.
  33304. */
  33305. VertexData.CreateTorus = function (options) {
  33306. var indices = [];
  33307. var positions = [];
  33308. var normals = [];
  33309. var uvs = [];
  33310. var diameter = options.diameter || 1;
  33311. var thickness = options.thickness || 0.5;
  33312. var tessellation = options.tessellation || 16;
  33313. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33314. var stride = tessellation + 1;
  33315. for (var i = 0; i <= tessellation; i++) {
  33316. var u = i / tessellation;
  33317. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33318. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33319. for (var j = 0; j <= tessellation; j++) {
  33320. var v = 1 - j / tessellation;
  33321. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33322. var dx = Math.cos(innerAngle);
  33323. var dy = Math.sin(innerAngle);
  33324. // Create a vertex.
  33325. var normal = new BABYLON.Vector3(dx, dy, 0);
  33326. var position = normal.scale(thickness / 2);
  33327. var textureCoordinate = new BABYLON.Vector2(u, v);
  33328. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33329. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33330. positions.push(position.x, position.y, position.z);
  33331. normals.push(normal.x, normal.y, normal.z);
  33332. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33333. // And create indices for two triangles.
  33334. var nextI = (i + 1) % stride;
  33335. var nextJ = (j + 1) % stride;
  33336. indices.push(i * stride + j);
  33337. indices.push(i * stride + nextJ);
  33338. indices.push(nextI * stride + j);
  33339. indices.push(i * stride + nextJ);
  33340. indices.push(nextI * stride + nextJ);
  33341. indices.push(nextI * stride + j);
  33342. }
  33343. }
  33344. // Sides
  33345. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33346. // Result
  33347. var vertexData = new VertexData();
  33348. vertexData.indices = indices;
  33349. vertexData.positions = positions;
  33350. vertexData.normals = normals;
  33351. vertexData.uvs = uvs;
  33352. return vertexData;
  33353. };
  33354. /**
  33355. * Creates the VertexData of the LineSystem.
  33356. */
  33357. VertexData.CreateLineSystem = function (options) {
  33358. var indices = [];
  33359. var positions = [];
  33360. var lines = options.lines;
  33361. var colors = options.colors;
  33362. var vertexColors = [];
  33363. var idx = 0;
  33364. for (var l = 0; l < lines.length; l++) {
  33365. var points = lines[l];
  33366. for (var index = 0; index < points.length; index++) {
  33367. positions.push(points[index].x, points[index].y, points[index].z);
  33368. if (colors) {
  33369. var color = colors[l];
  33370. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33371. }
  33372. if (index > 0) {
  33373. indices.push(idx - 1);
  33374. indices.push(idx);
  33375. }
  33376. idx++;
  33377. }
  33378. }
  33379. var vertexData = new VertexData();
  33380. vertexData.indices = indices;
  33381. vertexData.positions = positions;
  33382. if (colors) {
  33383. vertexData.colors = vertexColors;
  33384. }
  33385. return vertexData;
  33386. };
  33387. /**
  33388. * Create the VertexData of the DashedLines.
  33389. */
  33390. VertexData.CreateDashedLines = function (options) {
  33391. var dashSize = options.dashSize || 3;
  33392. var gapSize = options.gapSize || 1;
  33393. var dashNb = options.dashNb || 200;
  33394. var points = options.points;
  33395. var positions = new Array();
  33396. var indices = new Array();
  33397. var curvect = BABYLON.Vector3.Zero();
  33398. var lg = 0;
  33399. var nb = 0;
  33400. var shft = 0;
  33401. var dashshft = 0;
  33402. var curshft = 0;
  33403. var idx = 0;
  33404. var i = 0;
  33405. for (i = 0; i < points.length - 1; i++) {
  33406. points[i + 1].subtractToRef(points[i], curvect);
  33407. lg += curvect.length();
  33408. }
  33409. shft = lg / dashNb;
  33410. dashshft = dashSize * shft / (dashSize + gapSize);
  33411. for (i = 0; i < points.length - 1; i++) {
  33412. points[i + 1].subtractToRef(points[i], curvect);
  33413. nb = Math.floor(curvect.length() / shft);
  33414. curvect.normalize();
  33415. for (var j = 0; j < nb; j++) {
  33416. curshft = shft * j;
  33417. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33418. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33419. indices.push(idx, idx + 1);
  33420. idx += 2;
  33421. }
  33422. }
  33423. // Result
  33424. var vertexData = new VertexData();
  33425. vertexData.positions = positions;
  33426. vertexData.indices = indices;
  33427. return vertexData;
  33428. };
  33429. /**
  33430. * Creates the VertexData of the Ground.
  33431. */
  33432. VertexData.CreateGround = function (options) {
  33433. var indices = [];
  33434. var positions = [];
  33435. var normals = [];
  33436. var uvs = [];
  33437. var row, col;
  33438. var width = options.width || 1;
  33439. var height = options.height || 1;
  33440. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33441. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33442. for (row = 0; row <= subdivisionsY; row++) {
  33443. for (col = 0; col <= subdivisionsX; col++) {
  33444. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33445. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33446. positions.push(position.x, position.y, position.z);
  33447. normals.push(normal.x, normal.y, normal.z);
  33448. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33449. }
  33450. }
  33451. for (row = 0; row < subdivisionsY; row++) {
  33452. for (col = 0; col < subdivisionsX; col++) {
  33453. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33454. indices.push(col + 1 + row * (subdivisionsX + 1));
  33455. indices.push(col + row * (subdivisionsX + 1));
  33456. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33457. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33458. indices.push(col + row * (subdivisionsX + 1));
  33459. }
  33460. }
  33461. // Result
  33462. var vertexData = new VertexData();
  33463. vertexData.indices = indices;
  33464. vertexData.positions = positions;
  33465. vertexData.normals = normals;
  33466. vertexData.uvs = uvs;
  33467. return vertexData;
  33468. };
  33469. /**
  33470. * Creates the VertexData of the TiledGround.
  33471. */
  33472. VertexData.CreateTiledGround = function (options) {
  33473. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33474. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33475. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33476. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33477. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33478. var precision = options.precision || { w: 1, h: 1 };
  33479. var indices = new Array();
  33480. var positions = new Array();
  33481. var normals = new Array();
  33482. var uvs = new Array();
  33483. var row, col, tileRow, tileCol;
  33484. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33485. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33486. precision.w = (precision.w < 1) ? 1 : precision.w;
  33487. precision.h = (precision.h < 1) ? 1 : precision.h;
  33488. var tileSize = {
  33489. 'w': (xmax - xmin) / subdivisions.w,
  33490. 'h': (zmax - zmin) / subdivisions.h
  33491. };
  33492. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33493. // Indices
  33494. var base = positions.length / 3;
  33495. var rowLength = precision.w + 1;
  33496. for (row = 0; row < precision.h; row++) {
  33497. for (col = 0; col < precision.w; col++) {
  33498. var square = [
  33499. base + col + row * rowLength,
  33500. base + (col + 1) + row * rowLength,
  33501. base + (col + 1) + (row + 1) * rowLength,
  33502. base + col + (row + 1) * rowLength
  33503. ];
  33504. indices.push(square[1]);
  33505. indices.push(square[2]);
  33506. indices.push(square[3]);
  33507. indices.push(square[0]);
  33508. indices.push(square[1]);
  33509. indices.push(square[3]);
  33510. }
  33511. }
  33512. // Position, normals and uvs
  33513. var position = BABYLON.Vector3.Zero();
  33514. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33515. for (row = 0; row <= precision.h; row++) {
  33516. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33517. for (col = 0; col <= precision.w; col++) {
  33518. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33519. position.y = 0;
  33520. positions.push(position.x, position.y, position.z);
  33521. normals.push(normal.x, normal.y, normal.z);
  33522. uvs.push(col / precision.w, row / precision.h);
  33523. }
  33524. }
  33525. }
  33526. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33527. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33528. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33529. }
  33530. }
  33531. // Result
  33532. var vertexData = new VertexData();
  33533. vertexData.indices = indices;
  33534. vertexData.positions = positions;
  33535. vertexData.normals = normals;
  33536. vertexData.uvs = uvs;
  33537. return vertexData;
  33538. };
  33539. /**
  33540. * Creates the VertexData of the Ground designed from a heightmap.
  33541. */
  33542. VertexData.CreateGroundFromHeightMap = function (options) {
  33543. var indices = [];
  33544. var positions = [];
  33545. var normals = [];
  33546. var uvs = [];
  33547. var row, col;
  33548. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33549. // Vertices
  33550. for (row = 0; row <= options.subdivisions; row++) {
  33551. for (col = 0; col <= options.subdivisions; col++) {
  33552. 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));
  33553. // Compute height
  33554. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33555. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33556. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33557. var r = options.buffer[pos] / 255.0;
  33558. var g = options.buffer[pos + 1] / 255.0;
  33559. var b = options.buffer[pos + 2] / 255.0;
  33560. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33561. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33562. // Add vertex
  33563. positions.push(position.x, position.y, position.z);
  33564. normals.push(0, 0, 0);
  33565. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33566. }
  33567. }
  33568. // Indices
  33569. for (row = 0; row < options.subdivisions; row++) {
  33570. for (col = 0; col < options.subdivisions; col++) {
  33571. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33572. indices.push(col + 1 + row * (options.subdivisions + 1));
  33573. indices.push(col + row * (options.subdivisions + 1));
  33574. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33575. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33576. indices.push(col + row * (options.subdivisions + 1));
  33577. }
  33578. }
  33579. // Normals
  33580. VertexData.ComputeNormals(positions, indices, normals);
  33581. // Result
  33582. var vertexData = new VertexData();
  33583. vertexData.indices = indices;
  33584. vertexData.positions = positions;
  33585. vertexData.normals = normals;
  33586. vertexData.uvs = uvs;
  33587. return vertexData;
  33588. };
  33589. /**
  33590. * Creates the VertexData of the Plane.
  33591. */
  33592. VertexData.CreatePlane = function (options) {
  33593. var indices = [];
  33594. var positions = [];
  33595. var normals = [];
  33596. var uvs = [];
  33597. var width = options.width || options.size || 1;
  33598. var height = options.height || options.size || 1;
  33599. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33600. // Vertices
  33601. var halfWidth = width / 2.0;
  33602. var halfHeight = height / 2.0;
  33603. positions.push(-halfWidth, -halfHeight, 0);
  33604. normals.push(0, 0, -1.0);
  33605. uvs.push(0.0, 0.0);
  33606. positions.push(halfWidth, -halfHeight, 0);
  33607. normals.push(0, 0, -1.0);
  33608. uvs.push(1.0, 0.0);
  33609. positions.push(halfWidth, halfHeight, 0);
  33610. normals.push(0, 0, -1.0);
  33611. uvs.push(1.0, 1.0);
  33612. positions.push(-halfWidth, halfHeight, 0);
  33613. normals.push(0, 0, -1.0);
  33614. uvs.push(0.0, 1.0);
  33615. // Indices
  33616. indices.push(0);
  33617. indices.push(1);
  33618. indices.push(2);
  33619. indices.push(0);
  33620. indices.push(2);
  33621. indices.push(3);
  33622. // Sides
  33623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33624. // Result
  33625. var vertexData = new VertexData();
  33626. vertexData.indices = indices;
  33627. vertexData.positions = positions;
  33628. vertexData.normals = normals;
  33629. vertexData.uvs = uvs;
  33630. return vertexData;
  33631. };
  33632. /**
  33633. * Creates the VertexData of the Disc or regular Polygon.
  33634. */
  33635. VertexData.CreateDisc = function (options) {
  33636. var positions = new Array();
  33637. var indices = new Array();
  33638. var normals = new Array();
  33639. var uvs = new Array();
  33640. var radius = options.radius || 0.5;
  33641. var tessellation = options.tessellation || 64;
  33642. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33644. // positions and uvs
  33645. positions.push(0, 0, 0); // disc center first
  33646. uvs.push(0.5, 0.5);
  33647. var theta = Math.PI * 2 * arc;
  33648. var step = theta / tessellation;
  33649. for (var a = 0; a < theta; a += step) {
  33650. var x = Math.cos(a);
  33651. var y = Math.sin(a);
  33652. var u = (x + 1) / 2;
  33653. var v = (1 - y) / 2;
  33654. positions.push(radius * x, radius * y, 0);
  33655. uvs.push(u, v);
  33656. }
  33657. if (arc === 1) {
  33658. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33659. uvs.push(uvs[2], uvs[3]);
  33660. }
  33661. //indices
  33662. var vertexNb = positions.length / 3;
  33663. for (var i = 1; i < vertexNb - 1; i++) {
  33664. indices.push(i + 1, 0, i);
  33665. }
  33666. // result
  33667. VertexData.ComputeNormals(positions, indices, normals);
  33668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33669. var vertexData = new VertexData();
  33670. vertexData.indices = indices;
  33671. vertexData.positions = positions;
  33672. vertexData.normals = normals;
  33673. vertexData.uvs = uvs;
  33674. return vertexData;
  33675. };
  33676. /**
  33677. * Re-creates the VertexData of the Polygon for sideOrientation.
  33678. */
  33679. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33680. var faceUV = fUV || new Array(3);
  33681. var faceColors = fColors;
  33682. var colors = [];
  33683. // default face colors and UV if undefined
  33684. for (var f = 0; f < 3; f++) {
  33685. if (faceUV[f] === undefined) {
  33686. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33687. }
  33688. if (faceColors && faceColors[f] === undefined) {
  33689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33690. }
  33691. }
  33692. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33693. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33694. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33695. var indices = polygon.getIndices();
  33696. // set face colours and textures
  33697. var idx = 0;
  33698. var face = 0;
  33699. for (var index = 0; index < normals.length; index += 3) {
  33700. //Edge Face no. 1
  33701. if (Math.abs(normals[index + 1]) < 0.001) {
  33702. face = 1;
  33703. }
  33704. //Top Face no. 0
  33705. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33706. face = 0;
  33707. }
  33708. //Bottom Face no. 2
  33709. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33710. face = 2;
  33711. }
  33712. idx = index / 3;
  33713. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33714. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33715. if (faceColors) {
  33716. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33717. }
  33718. }
  33719. // sides
  33720. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33721. // Result
  33722. var vertexData = new VertexData();
  33723. vertexData.indices = indices;
  33724. vertexData.positions = positions;
  33725. vertexData.normals = normals;
  33726. vertexData.uvs = uvs;
  33727. if (faceColors) {
  33728. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33729. vertexData.colors = totalColors;
  33730. }
  33731. return vertexData;
  33732. };
  33733. /**
  33734. * Creates the VertexData of the IcoSphere.
  33735. */
  33736. VertexData.CreateIcoSphere = function (options) {
  33737. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33738. var radius = options.radius || 1;
  33739. var flat = (options.flat === undefined) ? true : options.flat;
  33740. var subdivisions = options.subdivisions || 4;
  33741. var radiusX = options.radiusX || radius;
  33742. var radiusY = options.radiusY || radius;
  33743. var radiusZ = options.radiusZ || radius;
  33744. var t = (1 + Math.sqrt(5)) / 2;
  33745. // 12 vertex x,y,z
  33746. var ico_vertices = [
  33747. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33748. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33749. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33750. ];
  33751. // index of 3 vertex makes a face of icopshere
  33752. var ico_indices = [
  33753. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33754. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33755. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33756. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33757. ];
  33758. // vertex for uv have aliased position, not for UV
  33759. var vertices_unalias_id = [
  33760. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33761. // vertex alias
  33762. 0,
  33763. 2,
  33764. 3,
  33765. 3,
  33766. 3,
  33767. 4,
  33768. 7,
  33769. 8,
  33770. 9,
  33771. 9,
  33772. 10,
  33773. 11 // 23: B + 12
  33774. ];
  33775. // uv as integer step (not pixels !)
  33776. var ico_vertexuv = [
  33777. 5, 1, 3, 1, 6, 4, 0, 0,
  33778. 5, 3, 4, 2, 2, 2, 4, 0,
  33779. 2, 0, 1, 1, 6, 0, 6, 2,
  33780. // vertex alias (for same vertex on different faces)
  33781. 0, 4,
  33782. 3, 3,
  33783. 4, 4,
  33784. 3, 1,
  33785. 4, 2,
  33786. 4, 4,
  33787. 0, 2,
  33788. 1, 1,
  33789. 2, 2,
  33790. 3, 3,
  33791. 1, 3,
  33792. 2, 4 // 23: B + 12
  33793. ];
  33794. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33795. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33796. // First island of uv mapping
  33797. // v = 4h 3+ 2
  33798. // v = 3h 9+ 4
  33799. // v = 2h 9+ 5 B
  33800. // v = 1h 9 1 0
  33801. // v = 0h 3 8 7 A
  33802. // u = 0 1 2 3 4 5 6 *a
  33803. // Second island of uv mapping
  33804. // v = 4h 0+ B+ 4+
  33805. // v = 3h A+ 2+
  33806. // v = 2h 7+ 6 3+
  33807. // v = 1h 8+ 3+
  33808. // v = 0h
  33809. // u = 0 1 2 3 4 5 6 *a
  33810. // Face layout on texture UV mapping
  33811. // ============
  33812. // \ 4 /\ 16 / ======
  33813. // \ / \ / /\ 11 /
  33814. // \/ 7 \/ / \ /
  33815. // ======= / 10 \/
  33816. // /\ 17 /\ =======
  33817. // / \ / \ \ 15 /\
  33818. // / 8 \/ 12 \ \ / \
  33819. // ============ \/ 6 \
  33820. // \ 18 /\ ============
  33821. // \ / \ \ 5 /\ 0 /
  33822. // \/ 13 \ \ / \ /
  33823. // ======= \/ 1 \/
  33824. // =============
  33825. // /\ 19 /\ 2 /\
  33826. // / \ / \ / \
  33827. // / 14 \/ 9 \/ 3 \
  33828. // ===================
  33829. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33830. var ustep = 138 / 1024;
  33831. var vstep = 239 / 1024;
  33832. var uoffset = 60 / 1024;
  33833. var voffset = 26 / 1024;
  33834. // Second island should have margin, not to touch the first island
  33835. // avoid any borderline artefact in pixel rounding
  33836. var island_u_offset = -40 / 1024;
  33837. var island_v_offset = +20 / 1024;
  33838. // face is either island 0 or 1 :
  33839. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33840. var island = [
  33841. 0, 0, 0, 0, 1,
  33842. 0, 0, 1, 1, 0,
  33843. 0, 0, 1, 1, 0,
  33844. 0, 1, 1, 1, 0 // 15 - 19
  33845. ];
  33846. var indices = new Array();
  33847. var positions = new Array();
  33848. var normals = new Array();
  33849. var uvs = new Array();
  33850. var current_indice = 0;
  33851. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33852. var face_vertex_pos = new Array(3);
  33853. var face_vertex_uv = new Array(3);
  33854. var v012;
  33855. for (v012 = 0; v012 < 3; v012++) {
  33856. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33857. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33858. }
  33859. // create all with normals
  33860. for (var face = 0; face < 20; face++) {
  33861. // 3 vertex per face
  33862. for (v012 = 0; v012 < 3; v012++) {
  33863. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33864. var v_id = ico_indices[3 * face + v012];
  33865. // vertex have 3D position (x,y,z)
  33866. 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]);
  33867. // Normalize to get normal, then scale to radius
  33868. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33869. // uv Coordinates from vertex ID
  33870. 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);
  33871. }
  33872. // Subdivide the face (interpolate pos, norm, uv)
  33873. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33874. // - norm is linear interpolation of vertex corner normal
  33875. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33876. // - uv is linear interpolation
  33877. //
  33878. // Topology is as below for sub-divide by 2
  33879. // vertex shown as v0,v1,v2
  33880. // interp index is i1 to progress in range [v0,v1[
  33881. // interp index is i2 to progress in range [v0,v2[
  33882. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33883. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33884. //
  33885. //
  33886. // i2 v2
  33887. // ^ ^
  33888. // / / \
  33889. // / / \
  33890. // / / \
  33891. // / / (0,1) \
  33892. // / #---------\
  33893. // / / \ (0,0)'/ \
  33894. // / / \ / \
  33895. // / / \ / \
  33896. // / / (0,0) \ / (1,0) \
  33897. // / #---------#---------\
  33898. // v0 v1
  33899. //
  33900. // --------------------> i1
  33901. //
  33902. // interp of (i1,i2):
  33903. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33904. // along i1 : lerp(x0,x1, i1/(S-i2))
  33905. //
  33906. // centroid of triangle is needed to get help normal computation
  33907. // (c1,c2) are used for centroid location
  33908. var interp_vertex = function (i1, i2, c1, c2) {
  33909. // vertex is interpolated from
  33910. // - face_vertex_pos[0..2]
  33911. // - face_vertex_uv[0..2]
  33912. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33913. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33914. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33915. pos_interp.normalize();
  33916. var vertex_normal;
  33917. if (flat) {
  33918. // in flat mode, recalculate normal as face centroid normal
  33919. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33920. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33921. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33922. }
  33923. else {
  33924. // in smooth mode, recalculate normal from each single vertex position
  33925. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33926. }
  33927. // Vertex normal need correction due to X,Y,Z radius scaling
  33928. vertex_normal.x /= radiusX;
  33929. vertex_normal.y /= radiusY;
  33930. vertex_normal.z /= radiusZ;
  33931. vertex_normal.normalize();
  33932. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33933. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33934. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33935. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33936. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33937. uvs.push(uv_interp.x, uv_interp.y);
  33938. // push each vertex has member of a face
  33939. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33940. indices.push(current_indice);
  33941. current_indice++;
  33942. };
  33943. for (var i2 = 0; i2 < subdivisions; i2++) {
  33944. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33945. // face : (i1,i2) for /\ :
  33946. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33947. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33948. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33949. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33950. if (i1 + i2 + 1 < subdivisions) {
  33951. // face : (i1,i2)' for \/ :
  33952. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33953. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33954. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33955. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33956. }
  33957. }
  33958. }
  33959. }
  33960. // Sides
  33961. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33962. // Result
  33963. var vertexData = new VertexData();
  33964. vertexData.indices = indices;
  33965. vertexData.positions = positions;
  33966. vertexData.normals = normals;
  33967. vertexData.uvs = uvs;
  33968. return vertexData;
  33969. };
  33970. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33971. /**
  33972. * Creates the VertexData of the Polyhedron.
  33973. */
  33974. VertexData.CreatePolyhedron = function (options) {
  33975. // provided polyhedron types :
  33976. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33977. // 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)
  33978. var polyhedra = [];
  33979. 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]] };
  33980. 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]] };
  33981. polyhedra[2] = {
  33982. 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]],
  33983. 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]]
  33984. };
  33985. polyhedra[3] = {
  33986. 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]],
  33987. 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]]
  33988. };
  33989. polyhedra[4] = {
  33990. 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]],
  33991. 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]]
  33992. };
  33993. 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]] };
  33994. 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]] };
  33995. 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]] };
  33996. 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]] };
  33997. 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]] };
  33998. 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]] };
  33999. 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]] };
  34000. 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]] };
  34001. 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]] };
  34002. polyhedra[14] = {
  34003. 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]],
  34004. 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]]
  34005. };
  34006. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34007. var size = options.size;
  34008. var sizeX = options.sizeX || size || 1;
  34009. var sizeY = options.sizeY || size || 1;
  34010. var sizeZ = options.sizeZ || size || 1;
  34011. var data = options.custom || polyhedra[type];
  34012. var nbfaces = data.face.length;
  34013. var faceUV = options.faceUV || new Array(nbfaces);
  34014. var faceColors = options.faceColors;
  34015. var flat = (options.flat === undefined) ? true : options.flat;
  34016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34017. var positions = new Array();
  34018. var indices = new Array();
  34019. var normals = new Array();
  34020. var uvs = new Array();
  34021. var colors = new Array();
  34022. var index = 0;
  34023. var faceIdx = 0; // face cursor in the array "indexes"
  34024. var indexes = new Array();
  34025. var i = 0;
  34026. var f = 0;
  34027. var u, v, ang, x, y, tmp;
  34028. // default face colors and UV if undefined
  34029. if (flat) {
  34030. for (f = 0; f < nbfaces; f++) {
  34031. if (faceColors && faceColors[f] === undefined) {
  34032. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34033. }
  34034. if (faceUV && faceUV[f] === undefined) {
  34035. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34036. }
  34037. }
  34038. }
  34039. if (!flat) {
  34040. for (i = 0; i < data.vertex.length; i++) {
  34041. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34042. uvs.push(0, 0);
  34043. }
  34044. for (f = 0; f < nbfaces; f++) {
  34045. for (i = 0; i < data.face[f].length - 2; i++) {
  34046. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34047. }
  34048. }
  34049. }
  34050. else {
  34051. for (f = 0; f < nbfaces; f++) {
  34052. var fl = data.face[f].length; // number of vertices of the current face
  34053. ang = 2 * Math.PI / fl;
  34054. x = 0.5 * Math.tan(ang / 2);
  34055. y = 0.5;
  34056. // positions, uvs, colors
  34057. for (i = 0; i < fl; i++) {
  34058. // positions
  34059. 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);
  34060. indexes.push(index);
  34061. index++;
  34062. // uvs
  34063. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34064. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34065. uvs.push(u, v);
  34066. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34067. y = x * Math.sin(ang) + y * Math.cos(ang);
  34068. x = tmp;
  34069. // colors
  34070. if (faceColors) {
  34071. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34072. }
  34073. }
  34074. // indices from indexes
  34075. for (i = 0; i < fl - 2; i++) {
  34076. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34077. }
  34078. faceIdx += fl;
  34079. }
  34080. }
  34081. VertexData.ComputeNormals(positions, indices, normals);
  34082. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34083. var vertexData = new VertexData();
  34084. vertexData.positions = positions;
  34085. vertexData.indices = indices;
  34086. vertexData.normals = normals;
  34087. vertexData.uvs = uvs;
  34088. if (faceColors && flat) {
  34089. vertexData.colors = colors;
  34090. }
  34091. return vertexData;
  34092. };
  34093. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34094. /**
  34095. * Creates the VertexData of the Torus Knot.
  34096. */
  34097. VertexData.CreateTorusKnot = function (options) {
  34098. var indices = new Array();
  34099. var positions = new Array();
  34100. var normals = new Array();
  34101. var uvs = new Array();
  34102. var radius = options.radius || 2;
  34103. var tube = options.tube || 0.5;
  34104. var radialSegments = options.radialSegments || 32;
  34105. var tubularSegments = options.tubularSegments || 32;
  34106. var p = options.p || 2;
  34107. var q = options.q || 3;
  34108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34109. // Helper
  34110. var getPos = function (angle) {
  34111. var cu = Math.cos(angle);
  34112. var su = Math.sin(angle);
  34113. var quOverP = q / p * angle;
  34114. var cs = Math.cos(quOverP);
  34115. var tx = radius * (2 + cs) * 0.5 * cu;
  34116. var ty = radius * (2 + cs) * su * 0.5;
  34117. var tz = radius * Math.sin(quOverP) * 0.5;
  34118. return new BABYLON.Vector3(tx, ty, tz);
  34119. };
  34120. // Vertices
  34121. var i;
  34122. var j;
  34123. for (i = 0; i <= radialSegments; i++) {
  34124. var modI = i % radialSegments;
  34125. var u = modI / radialSegments * 2 * p * Math.PI;
  34126. var p1 = getPos(u);
  34127. var p2 = getPos(u + 0.01);
  34128. var tang = p2.subtract(p1);
  34129. var n = p2.add(p1);
  34130. var bitan = BABYLON.Vector3.Cross(tang, n);
  34131. n = BABYLON.Vector3.Cross(bitan, tang);
  34132. bitan.normalize();
  34133. n.normalize();
  34134. for (j = 0; j < tubularSegments; j++) {
  34135. var modJ = j % tubularSegments;
  34136. var v = modJ / tubularSegments * 2 * Math.PI;
  34137. var cx = -tube * Math.cos(v);
  34138. var cy = tube * Math.sin(v);
  34139. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34140. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34141. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34142. uvs.push(i / radialSegments);
  34143. uvs.push(j / tubularSegments);
  34144. }
  34145. }
  34146. for (i = 0; i < radialSegments; i++) {
  34147. for (j = 0; j < tubularSegments; j++) {
  34148. var jNext = (j + 1) % tubularSegments;
  34149. var a = i * tubularSegments + j;
  34150. var b = (i + 1) * tubularSegments + j;
  34151. var c = (i + 1) * tubularSegments + jNext;
  34152. var d = i * tubularSegments + jNext;
  34153. indices.push(d);
  34154. indices.push(b);
  34155. indices.push(a);
  34156. indices.push(d);
  34157. indices.push(c);
  34158. indices.push(b);
  34159. }
  34160. }
  34161. // Normals
  34162. VertexData.ComputeNormals(positions, indices, normals);
  34163. // Sides
  34164. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34165. // Result
  34166. var vertexData = new VertexData();
  34167. vertexData.indices = indices;
  34168. vertexData.positions = positions;
  34169. vertexData.normals = normals;
  34170. vertexData.uvs = uvs;
  34171. return vertexData;
  34172. };
  34173. // Tools
  34174. /**
  34175. * @param {any} - positions (number[] or Float32Array)
  34176. * @param {any} - indices (number[] or Uint16Array)
  34177. * @param {any} - normals (number[] or Float32Array)
  34178. * options (optional) :
  34179. * facetPositions : optional array of facet positions (vector3)
  34180. * facetNormals : optional array of facet normals (vector3)
  34181. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34182. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34183. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34184. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34185. * bInfo : optional bounding info, required for facetPartitioning computation
  34186. * useRightHandedSystem: optional boolean to for right handed system computation
  34187. * depthSort : optional boolean to enable the facet depth sort computation
  34188. * distanceTo : optional Vector3 to compute the facet depth from this location
  34189. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34190. */
  34191. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34192. // temporary scalar variables
  34193. var index = 0; // facet index
  34194. var p1p2x = 0.0; // p1p2 vector x coordinate
  34195. var p1p2y = 0.0; // p1p2 vector y coordinate
  34196. var p1p2z = 0.0; // p1p2 vector z coordinate
  34197. var p3p2x = 0.0; // p3p2 vector x coordinate
  34198. var p3p2y = 0.0; // p3p2 vector y coordinate
  34199. var p3p2z = 0.0; // p3p2 vector z coordinate
  34200. var faceNormalx = 0.0; // facet normal x coordinate
  34201. var faceNormaly = 0.0; // facet normal y coordinate
  34202. var faceNormalz = 0.0; // facet normal z coordinate
  34203. var length = 0.0; // facet normal length before normalization
  34204. var v1x = 0; // vector1 x index in the positions array
  34205. var v1y = 0; // vector1 y index in the positions array
  34206. var v1z = 0; // vector1 z index in the positions array
  34207. var v2x = 0; // vector2 x index in the positions array
  34208. var v2y = 0; // vector2 y index in the positions array
  34209. var v2z = 0; // vector2 z index in the positions array
  34210. var v3x = 0; // vector3 x index in the positions array
  34211. var v3y = 0; // vector3 y index in the positions array
  34212. var v3z = 0; // vector3 z index in the positions array
  34213. var computeFacetNormals = false;
  34214. var computeFacetPositions = false;
  34215. var computeFacetPartitioning = false;
  34216. var computeDepthSort = false;
  34217. var faceNormalSign = 1;
  34218. var ratio = 0;
  34219. var distanceTo = null;
  34220. if (options) {
  34221. computeFacetNormals = (options.facetNormals) ? true : false;
  34222. computeFacetPositions = (options.facetPositions) ? true : false;
  34223. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34224. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34225. ratio = options.ratio || 0;
  34226. computeDepthSort = (options.depthSort) ? true : false;
  34227. distanceTo = (options.distanceTo);
  34228. if (computeDepthSort) {
  34229. if (distanceTo === undefined) {
  34230. distanceTo = BABYLON.Vector3.Zero();
  34231. }
  34232. var depthSortedFacets = options.depthSortedFacets;
  34233. }
  34234. }
  34235. // facetPartitioning reinit if needed
  34236. var xSubRatio = 0;
  34237. var ySubRatio = 0;
  34238. var zSubRatio = 0;
  34239. var subSq = 0;
  34240. if (computeFacetPartitioning && options && options.bbSize) {
  34241. var ox = 0; // X partitioning index for facet position
  34242. var oy = 0; // Y partinioning index for facet position
  34243. var oz = 0; // Z partinioning index for facet position
  34244. var b1x = 0; // X partitioning index for facet v1 vertex
  34245. var b1y = 0; // Y partitioning index for facet v1 vertex
  34246. var b1z = 0; // z partitioning index for facet v1 vertex
  34247. var b2x = 0; // X partitioning index for facet v2 vertex
  34248. var b2y = 0; // Y partitioning index for facet v2 vertex
  34249. var b2z = 0; // Z partitioning index for facet v2 vertex
  34250. var b3x = 0; // X partitioning index for facet v3 vertex
  34251. var b3y = 0; // Y partitioning index for facet v3 vertex
  34252. var b3z = 0; // Z partitioning index for facet v3 vertex
  34253. var block_idx_o = 0; // facet barycenter block index
  34254. var block_idx_v1 = 0; // v1 vertex block index
  34255. var block_idx_v2 = 0; // v2 vertex block index
  34256. var block_idx_v3 = 0; // v3 vertex block index
  34257. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34258. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34259. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34260. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34261. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34262. subSq = options.subDiv.max * options.subDiv.max;
  34263. options.facetPartitioning.length = 0;
  34264. }
  34265. // reset the normals
  34266. for (index = 0; index < positions.length; index++) {
  34267. normals[index] = 0.0;
  34268. }
  34269. // Loop : 1 indice triplet = 1 facet
  34270. var nbFaces = (indices.length / 3) | 0;
  34271. for (index = 0; index < nbFaces; index++) {
  34272. // get the indexes of the coordinates of each vertex of the facet
  34273. v1x = indices[index * 3] * 3;
  34274. v1y = v1x + 1;
  34275. v1z = v1x + 2;
  34276. v2x = indices[index * 3 + 1] * 3;
  34277. v2y = v2x + 1;
  34278. v2z = v2x + 2;
  34279. v3x = indices[index * 3 + 2] * 3;
  34280. v3y = v3x + 1;
  34281. v3z = v3x + 2;
  34282. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34283. p1p2y = positions[v1y] - positions[v2y];
  34284. p1p2z = positions[v1z] - positions[v2z];
  34285. p3p2x = positions[v3x] - positions[v2x];
  34286. p3p2y = positions[v3y] - positions[v2y];
  34287. p3p2z = positions[v3z] - positions[v2z];
  34288. // compute the face normal with the cross product
  34289. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34290. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34291. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34292. // normalize this normal and store it in the array facetData
  34293. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34294. length = (length === 0) ? 1.0 : length;
  34295. faceNormalx /= length;
  34296. faceNormaly /= length;
  34297. faceNormalz /= length;
  34298. if (computeFacetNormals && options) {
  34299. options.facetNormals[index].x = faceNormalx;
  34300. options.facetNormals[index].y = faceNormaly;
  34301. options.facetNormals[index].z = faceNormalz;
  34302. }
  34303. if (computeFacetPositions && options) {
  34304. // compute and the facet barycenter coordinates in the array facetPositions
  34305. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34306. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34307. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34308. }
  34309. if (computeFacetPartitioning && options) {
  34310. // store the facet indexes in arrays in the main facetPartitioning array :
  34311. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34312. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34313. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34314. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34315. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34316. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34317. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34318. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34319. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34320. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34321. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34322. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34323. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34324. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34325. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34326. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34327. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34328. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34329. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34330. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34331. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34332. // push each facet index in each block containing the vertex
  34333. options.facetPartitioning[block_idx_v1].push(index);
  34334. if (block_idx_v2 != block_idx_v1) {
  34335. options.facetPartitioning[block_idx_v2].push(index);
  34336. }
  34337. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34338. options.facetPartitioning[block_idx_v3].push(index);
  34339. }
  34340. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34341. options.facetPartitioning[block_idx_o].push(index);
  34342. }
  34343. }
  34344. if (computeDepthSort && options && options.facetPositions) {
  34345. var dsf = depthSortedFacets[index];
  34346. dsf.ind = index * 3;
  34347. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34348. }
  34349. // compute the normals anyway
  34350. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34351. normals[v1y] += faceNormaly;
  34352. normals[v1z] += faceNormalz;
  34353. normals[v2x] += faceNormalx;
  34354. normals[v2y] += faceNormaly;
  34355. normals[v2z] += faceNormalz;
  34356. normals[v3x] += faceNormalx;
  34357. normals[v3y] += faceNormaly;
  34358. normals[v3z] += faceNormalz;
  34359. }
  34360. // last normalization of each normal
  34361. for (index = 0; index < normals.length / 3; index++) {
  34362. faceNormalx = normals[index * 3];
  34363. faceNormaly = normals[index * 3 + 1];
  34364. faceNormalz = normals[index * 3 + 2];
  34365. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34366. length = (length === 0) ? 1.0 : length;
  34367. faceNormalx /= length;
  34368. faceNormaly /= length;
  34369. faceNormalz /= length;
  34370. normals[index * 3] = faceNormalx;
  34371. normals[index * 3 + 1] = faceNormaly;
  34372. normals[index * 3 + 2] = faceNormalz;
  34373. }
  34374. };
  34375. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34376. var li = indices.length;
  34377. var ln = normals.length;
  34378. var i;
  34379. var n;
  34380. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34381. switch (sideOrientation) {
  34382. case BABYLON.Mesh.FRONTSIDE:
  34383. // nothing changed
  34384. break;
  34385. case BABYLON.Mesh.BACKSIDE:
  34386. var tmp;
  34387. // indices
  34388. for (i = 0; i < li; i += 3) {
  34389. tmp = indices[i];
  34390. indices[i] = indices[i + 2];
  34391. indices[i + 2] = tmp;
  34392. }
  34393. // normals
  34394. for (n = 0; n < ln; n++) {
  34395. normals[n] = -normals[n];
  34396. }
  34397. break;
  34398. case BABYLON.Mesh.DOUBLESIDE:
  34399. // positions
  34400. var lp = positions.length;
  34401. var l = lp / 3;
  34402. for (var p = 0; p < lp; p++) {
  34403. positions[lp + p] = positions[p];
  34404. }
  34405. // indices
  34406. for (i = 0; i < li; i += 3) {
  34407. indices[i + li] = indices[i + 2] + l;
  34408. indices[i + 1 + li] = indices[i + 1] + l;
  34409. indices[i + 2 + li] = indices[i] + l;
  34410. }
  34411. // normals
  34412. for (n = 0; n < ln; n++) {
  34413. normals[ln + n] = -normals[n];
  34414. }
  34415. // uvs
  34416. var lu = uvs.length;
  34417. var u = 0;
  34418. for (u = 0; u < lu; u++) {
  34419. uvs[u + lu] = uvs[u];
  34420. }
  34421. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34422. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34423. u = 0;
  34424. for (i = 0; i < lu / 2; i++) {
  34425. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34426. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34427. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34428. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34429. u += 2;
  34430. }
  34431. break;
  34432. }
  34433. };
  34434. /**
  34435. * Creates a new VertexData from the imported parameters.
  34436. */
  34437. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34438. var vertexData = new VertexData();
  34439. // positions
  34440. var positions = parsedVertexData.positions;
  34441. if (positions) {
  34442. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34443. }
  34444. // normals
  34445. var normals = parsedVertexData.normals;
  34446. if (normals) {
  34447. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34448. }
  34449. // tangents
  34450. var tangents = parsedVertexData.tangents;
  34451. if (tangents) {
  34452. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34453. }
  34454. // uvs
  34455. var uvs = parsedVertexData.uvs;
  34456. if (uvs) {
  34457. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34458. }
  34459. // uv2s
  34460. var uv2s = parsedVertexData.uv2s;
  34461. if (uv2s) {
  34462. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34463. }
  34464. // uv3s
  34465. var uv3s = parsedVertexData.uv3s;
  34466. if (uv3s) {
  34467. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34468. }
  34469. // uv4s
  34470. var uv4s = parsedVertexData.uv4s;
  34471. if (uv4s) {
  34472. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34473. }
  34474. // uv5s
  34475. var uv5s = parsedVertexData.uv5s;
  34476. if (uv5s) {
  34477. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34478. }
  34479. // uv6s
  34480. var uv6s = parsedVertexData.uv6s;
  34481. if (uv6s) {
  34482. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34483. }
  34484. // colors
  34485. var colors = parsedVertexData.colors;
  34486. if (colors) {
  34487. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34488. }
  34489. // matricesIndices
  34490. var matricesIndices = parsedVertexData.matricesIndices;
  34491. if (matricesIndices) {
  34492. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34493. }
  34494. // matricesWeights
  34495. var matricesWeights = parsedVertexData.matricesWeights;
  34496. if (matricesWeights) {
  34497. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34498. }
  34499. // indices
  34500. var indices = parsedVertexData.indices;
  34501. if (indices) {
  34502. vertexData.indices = indices;
  34503. }
  34504. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34505. };
  34506. return VertexData;
  34507. }());
  34508. BABYLON.VertexData = VertexData;
  34509. })(BABYLON || (BABYLON = {}));
  34510. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34511. var BABYLON;
  34512. (function (BABYLON) {
  34513. /**
  34514. * Class used to store geometry data (vertex buffers + index buffer)
  34515. */
  34516. var Geometry = /** @class */ (function () {
  34517. /**
  34518. * Creates a new geometry
  34519. * @param id defines the unique ID
  34520. * @param scene defines the hosting scene
  34521. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34522. * @param updatable defines if geometry must be updatable (false by default)
  34523. * @param mesh defines the mesh that will be associated with the geometry
  34524. */
  34525. function Geometry(id, scene, vertexData, updatable, mesh) {
  34526. if (updatable === void 0) { updatable = false; }
  34527. if (mesh === void 0) { mesh = null; }
  34528. /**
  34529. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34530. */
  34531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34532. this._totalVertices = 0;
  34533. this._isDisposed = false;
  34534. this._indexBufferIsUpdatable = false;
  34535. this.id = id;
  34536. this._engine = scene.getEngine();
  34537. this._meshes = [];
  34538. this._scene = scene;
  34539. //Init vertex buffer cache
  34540. this._vertexBuffers = {};
  34541. this._indices = [];
  34542. this._updatable = updatable;
  34543. // vertexData
  34544. if (vertexData) {
  34545. this.setAllVerticesData(vertexData, updatable);
  34546. }
  34547. else {
  34548. this._totalVertices = 0;
  34549. this._indices = [];
  34550. }
  34551. if (this._engine.getCaps().vertexArrayObject) {
  34552. this._vertexArrayObjects = {};
  34553. }
  34554. // applyToMesh
  34555. if (mesh) {
  34556. if (mesh.getClassName() === "LinesMesh") {
  34557. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34558. this.updateExtend();
  34559. }
  34560. this.applyToMesh(mesh);
  34561. mesh.computeWorldMatrix(true);
  34562. }
  34563. }
  34564. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34565. /**
  34566. * 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
  34567. */
  34568. get: function () {
  34569. return this._boundingBias;
  34570. },
  34571. /**
  34572. * 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
  34573. */
  34574. set: function (value) {
  34575. if (this._boundingBias && this._boundingBias.equals(value)) {
  34576. return;
  34577. }
  34578. this._boundingBias = value.clone();
  34579. this.updateBoundingInfo(true, null);
  34580. },
  34581. enumerable: true,
  34582. configurable: true
  34583. });
  34584. /**
  34585. * Static function used to attach a new empty geometry to a mesh
  34586. * @param mesh defines the mesh to attach the geometry to
  34587. * @returns the new {BABYLON.Geometry}
  34588. */
  34589. Geometry.CreateGeometryForMesh = function (mesh) {
  34590. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34591. geometry.applyToMesh(mesh);
  34592. return geometry;
  34593. };
  34594. Object.defineProperty(Geometry.prototype, "extend", {
  34595. /**
  34596. * Gets the current extend of the geometry
  34597. */
  34598. get: function () {
  34599. return this._extend;
  34600. },
  34601. enumerable: true,
  34602. configurable: true
  34603. });
  34604. /**
  34605. * Gets the hosting scene
  34606. * @returns the hosting {BABYLON.Scene}
  34607. */
  34608. Geometry.prototype.getScene = function () {
  34609. return this._scene;
  34610. };
  34611. /**
  34612. * Gets the hosting engine
  34613. * @returns the hosting {BABYLON.Engine}
  34614. */
  34615. Geometry.prototype.getEngine = function () {
  34616. return this._engine;
  34617. };
  34618. /**
  34619. * Defines if the geometry is ready to use
  34620. * @returns true if the geometry is ready to be used
  34621. */
  34622. Geometry.prototype.isReady = function () {
  34623. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34624. };
  34625. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34626. /**
  34627. * Gets a value indicating that the geometry should not be serialized
  34628. */
  34629. get: function () {
  34630. for (var index = 0; index < this._meshes.length; index++) {
  34631. if (!this._meshes[index].doNotSerialize) {
  34632. return false;
  34633. }
  34634. }
  34635. return true;
  34636. },
  34637. enumerable: true,
  34638. configurable: true
  34639. });
  34640. /** @ignore */
  34641. Geometry.prototype._rebuild = function () {
  34642. if (this._vertexArrayObjects) {
  34643. this._vertexArrayObjects = {};
  34644. }
  34645. // Index buffer
  34646. if (this._meshes.length !== 0 && this._indices) {
  34647. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34648. }
  34649. // Vertex buffers
  34650. for (var key in this._vertexBuffers) {
  34651. var vertexBuffer = this._vertexBuffers[key];
  34652. vertexBuffer._rebuild();
  34653. }
  34654. };
  34655. /**
  34656. * Affects all gemetry data in one call
  34657. * @param vertexData defines the geometry data
  34658. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34659. */
  34660. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34661. vertexData.applyToGeometry(this, updatable);
  34662. this.notifyUpdate();
  34663. };
  34664. /**
  34665. * Set specific vertex data
  34666. * @param kind defines the data kind (Position, normal, etc...)
  34667. * @param data defines the vertex data to use
  34668. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34669. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34670. */
  34671. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34672. if (updatable === void 0) { updatable = false; }
  34673. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34674. this.setVerticesBuffer(buffer);
  34675. };
  34676. /**
  34677. * Removes a specific vertex data
  34678. * @param kind defines the data kind (Position, normal, etc...)
  34679. */
  34680. Geometry.prototype.removeVerticesData = function (kind) {
  34681. if (this._vertexBuffers[kind]) {
  34682. this._vertexBuffers[kind].dispose();
  34683. delete this._vertexBuffers[kind];
  34684. }
  34685. };
  34686. /**
  34687. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34688. * @param buffer defines the vertex buffer to use
  34689. */
  34690. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34691. var kind = buffer.getKind();
  34692. if (this._vertexBuffers[kind]) {
  34693. this._vertexBuffers[kind].dispose();
  34694. }
  34695. this._vertexBuffers[kind] = buffer;
  34696. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34697. var data = buffer.getData();
  34698. var stride = buffer.getStrideSize();
  34699. this._totalVertices = data.length / stride;
  34700. this.updateExtend(data, stride);
  34701. this._resetPointsArrayCache();
  34702. var meshes = this._meshes;
  34703. var numOfMeshes = meshes.length;
  34704. for (var index = 0; index < numOfMeshes; index++) {
  34705. var mesh = meshes[index];
  34706. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34707. mesh._createGlobalSubMesh(false);
  34708. mesh.computeWorldMatrix(true);
  34709. }
  34710. }
  34711. this.notifyUpdate(kind);
  34712. if (this._vertexArrayObjects) {
  34713. this._disposeVertexArrayObjects();
  34714. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34715. }
  34716. };
  34717. /**
  34718. * Update a specific vertex buffer
  34719. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34720. * It will do nothing if the buffer is not updatable
  34721. * @param kind defines the data kind (Position, normal, etc...)
  34722. * @param data defines the data to use
  34723. * @param offset defines the offset in the target buffer where to store the data
  34724. */
  34725. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34726. var vertexBuffer = this.getVertexBuffer(kind);
  34727. if (!vertexBuffer) {
  34728. return;
  34729. }
  34730. vertexBuffer.updateDirectly(data, offset);
  34731. this.notifyUpdate(kind);
  34732. };
  34733. /**
  34734. * Update a specific vertex buffer
  34735. * This function will create a new buffer if the current one is not updatable
  34736. * @param kind defines the data kind (Position, normal, etc...)
  34737. * @param data defines the data to use
  34738. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34739. */
  34740. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34741. if (updateExtends === void 0) { updateExtends = false; }
  34742. var vertexBuffer = this.getVertexBuffer(kind);
  34743. if (!vertexBuffer) {
  34744. return;
  34745. }
  34746. vertexBuffer.update(data);
  34747. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34748. var stride = vertexBuffer.getStrideSize();
  34749. this._totalVertices = data.length / stride;
  34750. this.updateBoundingInfo(updateExtends, data);
  34751. }
  34752. this.notifyUpdate(kind);
  34753. };
  34754. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34755. if (updateExtends) {
  34756. this.updateExtend(data);
  34757. }
  34758. var meshes = this._meshes;
  34759. var numOfMeshes = meshes.length;
  34760. this._resetPointsArrayCache();
  34761. for (var index = 0; index < numOfMeshes; index++) {
  34762. var mesh = meshes[index];
  34763. if (updateExtends) {
  34764. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34765. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34766. var subMesh = mesh.subMeshes[subIndex];
  34767. subMesh.refreshBoundingInfo();
  34768. }
  34769. }
  34770. }
  34771. };
  34772. /** @ignore */
  34773. Geometry.prototype._bind = function (effect, indexToBind) {
  34774. if (!effect) {
  34775. return;
  34776. }
  34777. if (indexToBind === undefined) {
  34778. indexToBind = this._indexBuffer;
  34779. }
  34780. var vbs = this.getVertexBuffers();
  34781. if (!vbs) {
  34782. return;
  34783. }
  34784. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34785. this._engine.bindBuffers(vbs, indexToBind, effect);
  34786. return;
  34787. }
  34788. // Using VAO
  34789. if (!this._vertexArrayObjects[effect.key]) {
  34790. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34791. }
  34792. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34793. };
  34794. /**
  34795. * Gets total number of vertices
  34796. * @returns the total number of vertices
  34797. */
  34798. Geometry.prototype.getTotalVertices = function () {
  34799. if (!this.isReady()) {
  34800. return 0;
  34801. }
  34802. return this._totalVertices;
  34803. };
  34804. /**
  34805. * Gets a specific vertex data attached to this geometry
  34806. * @param kind defines the data kind (Position, normal, etc...)
  34807. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34808. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34809. * @returns a float array containing vertex data
  34810. */
  34811. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34812. var vertexBuffer = this.getVertexBuffer(kind);
  34813. if (!vertexBuffer) {
  34814. return null;
  34815. }
  34816. var orig = vertexBuffer.getData();
  34817. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34818. return orig;
  34819. }
  34820. else {
  34821. var len = orig.length;
  34822. var copy = [];
  34823. for (var i = 0; i < len; i++) {
  34824. copy.push(orig[i]);
  34825. }
  34826. return copy;
  34827. }
  34828. };
  34829. /**
  34830. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34831. * @param kind defines the data kind (Position, normal, etc...)
  34832. * @returns true if the vertex buffer with the specified kind is updatable
  34833. */
  34834. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34835. var vb = this._vertexBuffers[kind];
  34836. if (!vb) {
  34837. return false;
  34838. }
  34839. return vb.isUpdatable();
  34840. };
  34841. /**
  34842. * Gets a specific vertex buffer
  34843. * @param kind defines the data kind (Position, normal, etc...)
  34844. * @returns a {BABYLON.VertexBuffer}
  34845. */
  34846. Geometry.prototype.getVertexBuffer = function (kind) {
  34847. if (!this.isReady()) {
  34848. return null;
  34849. }
  34850. return this._vertexBuffers[kind];
  34851. };
  34852. /**
  34853. * Returns all vertex buffers
  34854. * @return an object holding all vertex buffers indexed by kind
  34855. */
  34856. Geometry.prototype.getVertexBuffers = function () {
  34857. if (!this.isReady()) {
  34858. return null;
  34859. }
  34860. return this._vertexBuffers;
  34861. };
  34862. /**
  34863. * Gets a boolean indicating if specific vertex buffer is present
  34864. * @param kind defines the data kind (Position, normal, etc...)
  34865. * @returns true if data is present
  34866. */
  34867. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34868. if (!this._vertexBuffers) {
  34869. if (this._delayInfo) {
  34870. return this._delayInfo.indexOf(kind) !== -1;
  34871. }
  34872. return false;
  34873. }
  34874. return this._vertexBuffers[kind] !== undefined;
  34875. };
  34876. /**
  34877. * Gets a list of all attached data kinds (Position, normal, etc...)
  34878. * @returns a list of string containing all kinds
  34879. */
  34880. Geometry.prototype.getVerticesDataKinds = function () {
  34881. var result = [];
  34882. var kind;
  34883. if (!this._vertexBuffers && this._delayInfo) {
  34884. for (kind in this._delayInfo) {
  34885. result.push(kind);
  34886. }
  34887. }
  34888. else {
  34889. for (kind in this._vertexBuffers) {
  34890. result.push(kind);
  34891. }
  34892. }
  34893. return result;
  34894. };
  34895. /**
  34896. * Update index buffer
  34897. * @param indices defines the indices to store in the index buffer
  34898. * @param offset defines the offset in the target buffer where to store the data
  34899. */
  34900. Geometry.prototype.updateIndices = function (indices, offset) {
  34901. if (!this._indexBuffer) {
  34902. return;
  34903. }
  34904. if (!this._indexBufferIsUpdatable) {
  34905. this.setIndices(indices, null, true);
  34906. }
  34907. else {
  34908. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34909. }
  34910. };
  34911. /**
  34912. * Creates a new index buffer
  34913. * @param indices defines the indices to store in the index buffer
  34914. * @param totalVertices defines the total number of vertices (could be null)
  34915. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34916. */
  34917. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34918. if (totalVertices === void 0) { totalVertices = null; }
  34919. if (updatable === void 0) { updatable = false; }
  34920. if (this._indexBuffer) {
  34921. this._engine._releaseBuffer(this._indexBuffer);
  34922. }
  34923. this._disposeVertexArrayObjects();
  34924. this._indices = indices;
  34925. this._indexBufferIsUpdatable = updatable;
  34926. if (this._meshes.length !== 0 && this._indices) {
  34927. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34928. }
  34929. if (totalVertices != undefined) {
  34930. this._totalVertices = totalVertices;
  34931. }
  34932. var meshes = this._meshes;
  34933. var numOfMeshes = meshes.length;
  34934. for (var index = 0; index < numOfMeshes; index++) {
  34935. meshes[index]._createGlobalSubMesh(true);
  34936. }
  34937. this.notifyUpdate();
  34938. };
  34939. /**
  34940. * Return the total number of indices
  34941. * @returns the total number of indices
  34942. */
  34943. Geometry.prototype.getTotalIndices = function () {
  34944. if (!this.isReady()) {
  34945. return 0;
  34946. }
  34947. return this._indices.length;
  34948. };
  34949. /**
  34950. * Gets the index buffer array
  34951. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34952. * @returns the index buffer array
  34953. */
  34954. Geometry.prototype.getIndices = function (copyWhenShared) {
  34955. if (!this.isReady()) {
  34956. return null;
  34957. }
  34958. var orig = this._indices;
  34959. if (!copyWhenShared || this._meshes.length === 1) {
  34960. return orig;
  34961. }
  34962. else {
  34963. var len = orig.length;
  34964. var copy = [];
  34965. for (var i = 0; i < len; i++) {
  34966. copy.push(orig[i]);
  34967. }
  34968. return copy;
  34969. }
  34970. };
  34971. /**
  34972. * Gets the index buffer
  34973. * @return the index buffer
  34974. */
  34975. Geometry.prototype.getIndexBuffer = function () {
  34976. if (!this.isReady()) {
  34977. return null;
  34978. }
  34979. return this._indexBuffer;
  34980. };
  34981. /** @ignore */
  34982. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34983. if (effect === void 0) { effect = null; }
  34984. if (!effect || !this._vertexArrayObjects) {
  34985. return;
  34986. }
  34987. if (this._vertexArrayObjects[effect.key]) {
  34988. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34989. delete this._vertexArrayObjects[effect.key];
  34990. }
  34991. };
  34992. /**
  34993. * Release the associated resources for a specific mesh
  34994. * @param mesh defines the source mesh
  34995. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34996. */
  34997. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34998. var meshes = this._meshes;
  34999. var index = meshes.indexOf(mesh);
  35000. if (index === -1) {
  35001. return;
  35002. }
  35003. meshes.splice(index, 1);
  35004. mesh._geometry = null;
  35005. if (meshes.length === 0 && shouldDispose) {
  35006. this.dispose();
  35007. }
  35008. };
  35009. /**
  35010. * Apply current geometry to a given mesh
  35011. * @param mesh defines the mesh to apply geometry to
  35012. */
  35013. Geometry.prototype.applyToMesh = function (mesh) {
  35014. if (mesh._geometry === this) {
  35015. return;
  35016. }
  35017. var previousGeometry = mesh._geometry;
  35018. if (previousGeometry) {
  35019. previousGeometry.releaseForMesh(mesh);
  35020. }
  35021. var meshes = this._meshes;
  35022. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35023. mesh._geometry = this;
  35024. this._scene.pushGeometry(this);
  35025. meshes.push(mesh);
  35026. if (this.isReady()) {
  35027. this._applyToMesh(mesh);
  35028. }
  35029. else {
  35030. mesh._boundingInfo = this._boundingInfo;
  35031. }
  35032. };
  35033. Geometry.prototype.updateExtend = function (data, stride) {
  35034. if (data === void 0) { data = null; }
  35035. if (!data) {
  35036. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35037. }
  35038. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35039. };
  35040. Geometry.prototype._applyToMesh = function (mesh) {
  35041. var numOfMeshes = this._meshes.length;
  35042. // vertexBuffers
  35043. for (var kind in this._vertexBuffers) {
  35044. if (numOfMeshes === 1) {
  35045. this._vertexBuffers[kind].create();
  35046. }
  35047. var buffer = this._vertexBuffers[kind].getBuffer();
  35048. if (buffer)
  35049. buffer.references = numOfMeshes;
  35050. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35051. if (!this._extend) {
  35052. this.updateExtend(this._vertexBuffers[kind].getData());
  35053. }
  35054. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35055. mesh._createGlobalSubMesh(false);
  35056. //bounding info was just created again, world matrix should be applied again.
  35057. mesh._updateBoundingInfo();
  35058. }
  35059. }
  35060. // indexBuffer
  35061. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35062. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35063. }
  35064. if (this._indexBuffer) {
  35065. this._indexBuffer.references = numOfMeshes;
  35066. }
  35067. };
  35068. Geometry.prototype.notifyUpdate = function (kind) {
  35069. if (this.onGeometryUpdated) {
  35070. this.onGeometryUpdated(this, kind);
  35071. }
  35072. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35073. var mesh = _a[_i];
  35074. mesh._markSubMeshesAsAttributesDirty();
  35075. }
  35076. };
  35077. /**
  35078. * Load the geometry if it was flagged as delay loaded
  35079. * @param scene defines the hosting scene
  35080. * @param onLoaded defines a callback called when the geometry is loaded
  35081. */
  35082. Geometry.prototype.load = function (scene, onLoaded) {
  35083. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35084. return;
  35085. }
  35086. if (this.isReady()) {
  35087. if (onLoaded) {
  35088. onLoaded();
  35089. }
  35090. return;
  35091. }
  35092. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35093. this._queueLoad(scene, onLoaded);
  35094. };
  35095. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35096. var _this = this;
  35097. if (!this.delayLoadingFile) {
  35098. return;
  35099. }
  35100. scene._addPendingData(this);
  35101. scene._loadFile(this.delayLoadingFile, function (data) {
  35102. if (!_this._delayLoadingFunction) {
  35103. return;
  35104. }
  35105. _this._delayLoadingFunction(JSON.parse(data), _this);
  35106. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35107. _this._delayInfo = [];
  35108. scene._removePendingData(_this);
  35109. var meshes = _this._meshes;
  35110. var numOfMeshes = meshes.length;
  35111. for (var index = 0; index < numOfMeshes; index++) {
  35112. _this._applyToMesh(meshes[index]);
  35113. }
  35114. if (onLoaded) {
  35115. onLoaded();
  35116. }
  35117. }, undefined, true);
  35118. };
  35119. /**
  35120. * Invert the geometry to move from a right handed system to a left handed one.
  35121. */
  35122. Geometry.prototype.toLeftHanded = function () {
  35123. // Flip faces
  35124. var tIndices = this.getIndices(false);
  35125. if (tIndices != null && tIndices.length > 0) {
  35126. for (var i = 0; i < tIndices.length; i += 3) {
  35127. var tTemp = tIndices[i + 0];
  35128. tIndices[i + 0] = tIndices[i + 2];
  35129. tIndices[i + 2] = tTemp;
  35130. }
  35131. this.setIndices(tIndices);
  35132. }
  35133. // Negate position.z
  35134. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35135. if (tPositions != null && tPositions.length > 0) {
  35136. for (var i = 0; i < tPositions.length; i += 3) {
  35137. tPositions[i + 2] = -tPositions[i + 2];
  35138. }
  35139. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35140. }
  35141. // Negate normal.z
  35142. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35143. if (tNormals != null && tNormals.length > 0) {
  35144. for (var i = 0; i < tNormals.length; i += 3) {
  35145. tNormals[i + 2] = -tNormals[i + 2];
  35146. }
  35147. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35148. }
  35149. };
  35150. // Cache
  35151. /** @ignore */
  35152. Geometry.prototype._resetPointsArrayCache = function () {
  35153. this._positions = null;
  35154. };
  35155. /** @ignore */
  35156. Geometry.prototype._generatePointsArray = function () {
  35157. if (this._positions)
  35158. return true;
  35159. this._positions = [];
  35160. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35161. if (!data) {
  35162. return false;
  35163. }
  35164. for (var index = 0; index < data.length; index += 3) {
  35165. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35166. }
  35167. return true;
  35168. };
  35169. /**
  35170. * Gets a value indicating if the geometry is disposed
  35171. * @returns true if the geometry was disposed
  35172. */
  35173. Geometry.prototype.isDisposed = function () {
  35174. return this._isDisposed;
  35175. };
  35176. Geometry.prototype._disposeVertexArrayObjects = function () {
  35177. if (this._vertexArrayObjects) {
  35178. for (var kind in this._vertexArrayObjects) {
  35179. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35180. }
  35181. this._vertexArrayObjects = {};
  35182. }
  35183. };
  35184. /**
  35185. * Free all associated resources
  35186. */
  35187. Geometry.prototype.dispose = function () {
  35188. var meshes = this._meshes;
  35189. var numOfMeshes = meshes.length;
  35190. var index;
  35191. for (index = 0; index < numOfMeshes; index++) {
  35192. this.releaseForMesh(meshes[index]);
  35193. }
  35194. this._meshes = [];
  35195. this._disposeVertexArrayObjects();
  35196. for (var kind in this._vertexBuffers) {
  35197. this._vertexBuffers[kind].dispose();
  35198. }
  35199. this._vertexBuffers = {};
  35200. this._totalVertices = 0;
  35201. if (this._indexBuffer) {
  35202. this._engine._releaseBuffer(this._indexBuffer);
  35203. }
  35204. this._indexBuffer = null;
  35205. this._indices = [];
  35206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35207. this.delayLoadingFile = null;
  35208. this._delayLoadingFunction = null;
  35209. this._delayInfo = [];
  35210. this._boundingInfo = null;
  35211. this._scene.removeGeometry(this);
  35212. this._isDisposed = true;
  35213. };
  35214. /**
  35215. * Clone the current geometry into a new geometry
  35216. * @param id defines the unique ID of the new geometry
  35217. * @returns a new geometry object
  35218. */
  35219. Geometry.prototype.copy = function (id) {
  35220. var vertexData = new BABYLON.VertexData();
  35221. vertexData.indices = [];
  35222. var indices = this.getIndices();
  35223. if (indices) {
  35224. for (var index = 0; index < indices.length; index++) {
  35225. vertexData.indices.push(indices[index]);
  35226. }
  35227. }
  35228. var updatable = false;
  35229. var stopChecking = false;
  35230. var kind;
  35231. for (kind in this._vertexBuffers) {
  35232. // using slice() to make a copy of the array and not just reference it
  35233. var data = this.getVerticesData(kind);
  35234. if (data instanceof Float32Array) {
  35235. vertexData.set(new Float32Array(data), kind);
  35236. }
  35237. else {
  35238. vertexData.set(data.slice(0), kind);
  35239. }
  35240. if (!stopChecking) {
  35241. var vb = this.getVertexBuffer(kind);
  35242. if (vb) {
  35243. updatable = vb.isUpdatable();
  35244. stopChecking = !updatable;
  35245. }
  35246. }
  35247. }
  35248. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35249. geometry.delayLoadState = this.delayLoadState;
  35250. geometry.delayLoadingFile = this.delayLoadingFile;
  35251. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35252. for (kind in this._delayInfo) {
  35253. geometry._delayInfo = geometry._delayInfo || [];
  35254. geometry._delayInfo.push(kind);
  35255. }
  35256. // Bounding info
  35257. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35258. return geometry;
  35259. };
  35260. /**
  35261. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35262. * @return a JSON representation of the current geometry data (without the vertices data)
  35263. */
  35264. Geometry.prototype.serialize = function () {
  35265. var serializationObject = {};
  35266. serializationObject.id = this.id;
  35267. serializationObject.updatable = this._updatable;
  35268. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35269. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35270. }
  35271. return serializationObject;
  35272. };
  35273. Geometry.prototype.toNumberArray = function (origin) {
  35274. if (Array.isArray(origin)) {
  35275. return origin;
  35276. }
  35277. else {
  35278. return Array.prototype.slice.call(origin);
  35279. }
  35280. };
  35281. /**
  35282. * Serialize all vertices data into a JSON oject
  35283. * @returns a JSON representation of the current geometry data
  35284. */
  35285. Geometry.prototype.serializeVerticeData = function () {
  35286. var serializationObject = this.serialize();
  35287. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35288. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35289. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35290. serializationObject.positions._updatable = true;
  35291. }
  35292. }
  35293. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35294. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35295. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35296. serializationObject.normals._updatable = true;
  35297. }
  35298. }
  35299. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35300. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35301. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35302. serializationObject.tangets._updatable = true;
  35303. }
  35304. }
  35305. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35306. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35307. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35308. serializationObject.uvs._updatable = true;
  35309. }
  35310. }
  35311. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35312. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35313. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35314. serializationObject.uv2s._updatable = true;
  35315. }
  35316. }
  35317. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35318. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35319. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35320. serializationObject.uv3s._updatable = true;
  35321. }
  35322. }
  35323. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35324. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35325. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35326. serializationObject.uv4s._updatable = true;
  35327. }
  35328. }
  35329. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35330. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35331. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35332. serializationObject.uv5s._updatable = true;
  35333. }
  35334. }
  35335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35336. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35337. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35338. serializationObject.uv6s._updatable = true;
  35339. }
  35340. }
  35341. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35342. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35343. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35344. serializationObject.colors._updatable = true;
  35345. }
  35346. }
  35347. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35348. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35349. serializationObject.matricesIndices._isExpanded = true;
  35350. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35351. serializationObject.matricesIndices._updatable = true;
  35352. }
  35353. }
  35354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35355. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35356. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35357. serializationObject.matricesWeights._updatable = true;
  35358. }
  35359. }
  35360. serializationObject.indices = this.toNumberArray(this.getIndices());
  35361. return serializationObject;
  35362. };
  35363. // Statics
  35364. /**
  35365. * Extracts a clone of a mesh geometry
  35366. * @param mesh defines the source mesh
  35367. * @param id defines the unique ID of the new geometry object
  35368. * @returns the new geometry object
  35369. */
  35370. Geometry.ExtractFromMesh = function (mesh, id) {
  35371. var geometry = mesh._geometry;
  35372. if (!geometry) {
  35373. return null;
  35374. }
  35375. return geometry.copy(id);
  35376. };
  35377. /**
  35378. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35379. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35380. * Be aware Math.random() could cause collisions, but:
  35381. * "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"
  35382. * @returns a string containing a new GUID
  35383. */
  35384. Geometry.RandomId = function () {
  35385. return BABYLON.Tools.RandomId();
  35386. };
  35387. /** @ignore */
  35388. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35389. var scene = mesh.getScene();
  35390. // Geometry
  35391. var geometryId = parsedGeometry.geometryId;
  35392. if (geometryId) {
  35393. var geometry = scene.getGeometryByID(geometryId);
  35394. if (geometry) {
  35395. geometry.applyToMesh(mesh);
  35396. }
  35397. }
  35398. else if (parsedGeometry instanceof ArrayBuffer) {
  35399. var binaryInfo = mesh._binaryInfo;
  35400. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35401. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35402. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35403. }
  35404. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35405. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35406. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35407. }
  35408. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35409. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35410. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35411. }
  35412. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35413. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35414. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35415. }
  35416. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35417. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35418. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35419. }
  35420. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35421. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35422. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35423. }
  35424. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35425. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35426. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35427. }
  35428. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35429. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35430. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35431. }
  35432. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35433. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35434. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35435. }
  35436. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35437. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35438. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35439. }
  35440. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35441. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35442. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35443. }
  35444. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35445. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35447. }
  35448. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35449. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35450. mesh.setIndices(indicesData, null);
  35451. }
  35452. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35453. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35454. mesh.subMeshes = [];
  35455. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35456. var materialIndex = subMeshesData[(i * 5) + 0];
  35457. var verticesStart = subMeshesData[(i * 5) + 1];
  35458. var verticesCount = subMeshesData[(i * 5) + 2];
  35459. var indexStart = subMeshesData[(i * 5) + 3];
  35460. var indexCount = subMeshesData[(i * 5) + 4];
  35461. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35462. }
  35463. }
  35464. }
  35465. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35466. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35467. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35468. if (parsedGeometry.tangents) {
  35469. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35470. }
  35471. if (parsedGeometry.uvs) {
  35472. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35473. }
  35474. if (parsedGeometry.uvs2) {
  35475. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35476. }
  35477. if (parsedGeometry.uvs3) {
  35478. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35479. }
  35480. if (parsedGeometry.uvs4) {
  35481. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35482. }
  35483. if (parsedGeometry.uvs5) {
  35484. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35485. }
  35486. if (parsedGeometry.uvs6) {
  35487. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35488. }
  35489. if (parsedGeometry.colors) {
  35490. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35491. }
  35492. if (parsedGeometry.matricesIndices) {
  35493. if (!parsedGeometry.matricesIndices._isExpanded) {
  35494. var floatIndices = [];
  35495. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35496. var matricesIndex = parsedGeometry.matricesIndices[i];
  35497. floatIndices.push(matricesIndex & 0x000000FF);
  35498. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35499. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35500. floatIndices.push(matricesIndex >> 24);
  35501. }
  35502. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35503. }
  35504. else {
  35505. delete parsedGeometry.matricesIndices._isExpanded;
  35506. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35507. }
  35508. }
  35509. if (parsedGeometry.matricesIndicesExtra) {
  35510. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35511. var floatIndices = [];
  35512. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35513. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35514. floatIndices.push(matricesIndex & 0x000000FF);
  35515. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35516. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35517. floatIndices.push(matricesIndex >> 24);
  35518. }
  35519. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35520. }
  35521. else {
  35522. delete parsedGeometry.matricesIndices._isExpanded;
  35523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35524. }
  35525. }
  35526. if (parsedGeometry.matricesWeights) {
  35527. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35528. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35529. }
  35530. if (parsedGeometry.matricesWeightsExtra) {
  35531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35532. }
  35533. mesh.setIndices(parsedGeometry.indices, null);
  35534. }
  35535. // SubMeshes
  35536. if (parsedGeometry.subMeshes) {
  35537. mesh.subMeshes = [];
  35538. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35539. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35540. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35541. }
  35542. }
  35543. // Flat shading
  35544. if (mesh._shouldGenerateFlatShading) {
  35545. mesh.convertToFlatShadedMesh();
  35546. delete mesh._shouldGenerateFlatShading;
  35547. }
  35548. // Update
  35549. mesh.computeWorldMatrix(true);
  35550. // Octree
  35551. var sceneOctree = scene.selectionOctree;
  35552. if (sceneOctree !== undefined && sceneOctree !== null) {
  35553. sceneOctree.addMesh(mesh);
  35554. }
  35555. };
  35556. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35557. var epsilon = 1e-3;
  35558. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35559. return;
  35560. }
  35561. var noInfluenceBoneIndex = 0.0;
  35562. if (parsedGeometry.skeletonId > -1) {
  35563. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35564. if (!skeleton) {
  35565. return;
  35566. }
  35567. noInfluenceBoneIndex = skeleton.bones.length;
  35568. }
  35569. else {
  35570. return;
  35571. }
  35572. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35573. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35574. var matricesWeights = parsedGeometry.matricesWeights;
  35575. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35576. var influencers = parsedGeometry.numBoneInfluencer;
  35577. var size = matricesWeights.length;
  35578. for (var i = 0; i < size; i += 4) {
  35579. var weight = 0.0;
  35580. var firstZeroWeight = -1;
  35581. for (var j = 0; j < 4; j++) {
  35582. var w = matricesWeights[i + j];
  35583. weight += w;
  35584. if (w < epsilon && firstZeroWeight < 0) {
  35585. firstZeroWeight = j;
  35586. }
  35587. }
  35588. if (matricesWeightsExtra) {
  35589. for (var j = 0; j < 4; j++) {
  35590. var w = matricesWeightsExtra[i + j];
  35591. weight += w;
  35592. if (w < epsilon && firstZeroWeight < 0) {
  35593. firstZeroWeight = j + 4;
  35594. }
  35595. }
  35596. }
  35597. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35598. firstZeroWeight = influencers - 1;
  35599. }
  35600. if (weight > epsilon) {
  35601. var mweight = 1.0 / weight;
  35602. for (var j = 0; j < 4; j++) {
  35603. matricesWeights[i + j] *= mweight;
  35604. }
  35605. if (matricesWeightsExtra) {
  35606. for (var j = 0; j < 4; j++) {
  35607. matricesWeightsExtra[i + j] *= mweight;
  35608. }
  35609. }
  35610. }
  35611. else {
  35612. if (firstZeroWeight >= 4) {
  35613. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35614. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35615. }
  35616. else {
  35617. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35618. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35619. }
  35620. }
  35621. }
  35622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35623. if (parsedGeometry.matricesWeightsExtra) {
  35624. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35625. }
  35626. };
  35627. /**
  35628. * Create a new geometry from persisted data (Using .babylon file format)
  35629. * @param parsedVertexData defines the persisted data
  35630. * @param scene defines the hosting scene
  35631. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35632. * @returns the new geometry object
  35633. */
  35634. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35635. if (scene.getGeometryByID(parsedVertexData.id)) {
  35636. return null; // null since geometry could be something else than a box...
  35637. }
  35638. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35639. if (BABYLON.Tags) {
  35640. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35641. }
  35642. if (parsedVertexData.delayLoadingFile) {
  35643. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35644. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35645. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35646. geometry._delayInfo = [];
  35647. if (parsedVertexData.hasUVs) {
  35648. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35649. }
  35650. if (parsedVertexData.hasUVs2) {
  35651. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35652. }
  35653. if (parsedVertexData.hasUVs3) {
  35654. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35655. }
  35656. if (parsedVertexData.hasUVs4) {
  35657. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35658. }
  35659. if (parsedVertexData.hasUVs5) {
  35660. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35661. }
  35662. if (parsedVertexData.hasUVs6) {
  35663. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35664. }
  35665. if (parsedVertexData.hasColors) {
  35666. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35667. }
  35668. if (parsedVertexData.hasMatricesIndices) {
  35669. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35670. }
  35671. if (parsedVertexData.hasMatricesWeights) {
  35672. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35673. }
  35674. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35675. }
  35676. else {
  35677. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35678. }
  35679. scene.pushGeometry(geometry, true);
  35680. return geometry;
  35681. };
  35682. return Geometry;
  35683. }());
  35684. BABYLON.Geometry = Geometry;
  35685. // Primitives
  35686. /// Abstract class
  35687. /**
  35688. * Abstract class used to provide common services for all typed geometries
  35689. */
  35690. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35691. __extends(_PrimitiveGeometry, _super);
  35692. /**
  35693. * Creates a new typed geometry
  35694. * @param id defines the unique ID of the geometry
  35695. * @param scene defines the hosting scene
  35696. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35697. * @param mesh defines the hosting mesh (can be null)
  35698. */
  35699. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35700. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35701. if (mesh === void 0) { mesh = null; }
  35702. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35703. _this._canBeRegenerated = _canBeRegenerated;
  35704. _this._beingRegenerated = true;
  35705. _this.regenerate();
  35706. _this._beingRegenerated = false;
  35707. return _this;
  35708. }
  35709. /**
  35710. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35711. * @returns true if the geometry can be regenerated
  35712. */
  35713. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35714. return this._canBeRegenerated;
  35715. };
  35716. /**
  35717. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35718. */
  35719. _PrimitiveGeometry.prototype.regenerate = function () {
  35720. if (!this._canBeRegenerated) {
  35721. return;
  35722. }
  35723. this._beingRegenerated = true;
  35724. this.setAllVerticesData(this._regenerateVertexData(), false);
  35725. this._beingRegenerated = false;
  35726. };
  35727. /**
  35728. * Clone the geometry
  35729. * @param id defines the unique ID of the new geometry
  35730. * @returns the new geometry
  35731. */
  35732. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35733. return _super.prototype.copy.call(this, id);
  35734. };
  35735. // overrides
  35736. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35737. if (!this._beingRegenerated) {
  35738. return;
  35739. }
  35740. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35741. };
  35742. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35743. if (!this._beingRegenerated) {
  35744. return;
  35745. }
  35746. _super.prototype.setVerticesData.call(this, kind, data, false);
  35747. };
  35748. // to override
  35749. /** @ignore */
  35750. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35751. throw new Error("Abstract method");
  35752. };
  35753. _PrimitiveGeometry.prototype.copy = function (id) {
  35754. throw new Error("Must be overriden in sub-classes.");
  35755. };
  35756. _PrimitiveGeometry.prototype.serialize = function () {
  35757. var serializationObject = _super.prototype.serialize.call(this);
  35758. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35759. return serializationObject;
  35760. };
  35761. return _PrimitiveGeometry;
  35762. }(Geometry));
  35763. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35764. /**
  35765. * Creates a ribbon geometry
  35766. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35767. */
  35768. var RibbonGeometry = /** @class */ (function (_super) {
  35769. __extends(RibbonGeometry, _super);
  35770. /**
  35771. * Creates a ribbon geometry
  35772. * @param id defines the unique ID of the geometry
  35773. * @param scene defines the hosting scene
  35774. * @param pathArray defines the array of paths to use
  35775. * @param closeArray defines if the last path and the first path must be joined
  35776. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35777. * @param offset defines the offset between points
  35778. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35779. * @param mesh defines the hosting mesh (can be null)
  35780. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35781. */
  35782. function RibbonGeometry(id, scene,
  35783. /**
  35784. * Defines the array of paths to use
  35785. */
  35786. pathArray,
  35787. /**
  35788. * Defines if the last and first points of each path in your pathArray must be joined
  35789. */
  35790. closeArray,
  35791. /**
  35792. * Defines if the last and first points of each path in your pathArray must be joined
  35793. */
  35794. closePath,
  35795. /**
  35796. * Defines the offset between points
  35797. */
  35798. offset, canBeRegenerated, mesh,
  35799. /**
  35800. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35801. */
  35802. side) {
  35803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35805. _this.pathArray = pathArray;
  35806. _this.closeArray = closeArray;
  35807. _this.closePath = closePath;
  35808. _this.offset = offset;
  35809. _this.side = side;
  35810. return _this;
  35811. }
  35812. /** @ignore */
  35813. RibbonGeometry.prototype._regenerateVertexData = function () {
  35814. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35815. };
  35816. RibbonGeometry.prototype.copy = function (id) {
  35817. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35818. };
  35819. return RibbonGeometry;
  35820. }(_PrimitiveGeometry));
  35821. BABYLON.RibbonGeometry = RibbonGeometry;
  35822. /**
  35823. * Creates a box geometry
  35824. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35825. */
  35826. var BoxGeometry = /** @class */ (function (_super) {
  35827. __extends(BoxGeometry, _super);
  35828. /**
  35829. * Creates a box geometry
  35830. * @param id defines the unique ID of the geometry
  35831. * @param scene defines the hosting scene
  35832. * @param size defines the zise of the box (width, height and depth are the same)
  35833. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35834. * @param mesh defines the hosting mesh (can be null)
  35835. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35836. */
  35837. function BoxGeometry(id, scene,
  35838. /**
  35839. * Defines the zise of the box (width, height and depth are the same)
  35840. */
  35841. size, canBeRegenerated, mesh,
  35842. /**
  35843. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35844. */
  35845. side) {
  35846. if (mesh === void 0) { mesh = null; }
  35847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35849. _this.size = size;
  35850. _this.side = side;
  35851. return _this;
  35852. }
  35853. BoxGeometry.prototype._regenerateVertexData = function () {
  35854. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35855. };
  35856. BoxGeometry.prototype.copy = function (id) {
  35857. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35858. };
  35859. BoxGeometry.prototype.serialize = function () {
  35860. var serializationObject = _super.prototype.serialize.call(this);
  35861. serializationObject.size = this.size;
  35862. return serializationObject;
  35863. };
  35864. BoxGeometry.Parse = function (parsedBox, scene) {
  35865. if (scene.getGeometryByID(parsedBox.id)) {
  35866. return null; // null since geometry could be something else than a box...
  35867. }
  35868. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35869. if (BABYLON.Tags) {
  35870. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35871. }
  35872. scene.pushGeometry(box, true);
  35873. return box;
  35874. };
  35875. return BoxGeometry;
  35876. }(_PrimitiveGeometry));
  35877. BABYLON.BoxGeometry = BoxGeometry;
  35878. /**
  35879. * Creates a sphere geometry
  35880. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35881. */
  35882. var SphereGeometry = /** @class */ (function (_super) {
  35883. __extends(SphereGeometry, _super);
  35884. /**
  35885. * Create a new sphere geometry
  35886. * @param id defines the unique ID of the geometry
  35887. * @param scene defines the hosting scene
  35888. * @param segments defines the number of segments to use to create the sphere
  35889. * @param diameter defines the diameter of the sphere
  35890. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35891. * @param mesh defines the hosting mesh (can be null)
  35892. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35893. */
  35894. function SphereGeometry(id, scene,
  35895. /**
  35896. * Defines the number of segments to use to create the sphere
  35897. */
  35898. segments,
  35899. /**
  35900. * Defines the diameter of the sphere
  35901. */
  35902. diameter, canBeRegenerated, mesh,
  35903. /**
  35904. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35905. */
  35906. side) {
  35907. if (mesh === void 0) { mesh = null; }
  35908. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35909. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35910. _this.segments = segments;
  35911. _this.diameter = diameter;
  35912. _this.side = side;
  35913. return _this;
  35914. }
  35915. SphereGeometry.prototype._regenerateVertexData = function () {
  35916. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35917. };
  35918. SphereGeometry.prototype.copy = function (id) {
  35919. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35920. };
  35921. SphereGeometry.prototype.serialize = function () {
  35922. var serializationObject = _super.prototype.serialize.call(this);
  35923. serializationObject.segments = this.segments;
  35924. serializationObject.diameter = this.diameter;
  35925. return serializationObject;
  35926. };
  35927. SphereGeometry.Parse = function (parsedSphere, scene) {
  35928. if (scene.getGeometryByID(parsedSphere.id)) {
  35929. return null; // null since geometry could be something else than a sphere...
  35930. }
  35931. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35932. if (BABYLON.Tags) {
  35933. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35934. }
  35935. scene.pushGeometry(sphere, true);
  35936. return sphere;
  35937. };
  35938. return SphereGeometry;
  35939. }(_PrimitiveGeometry));
  35940. BABYLON.SphereGeometry = SphereGeometry;
  35941. /**
  35942. * Creates a disc geometry
  35943. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35944. */
  35945. var DiscGeometry = /** @class */ (function (_super) {
  35946. __extends(DiscGeometry, _super);
  35947. /**
  35948. * Creates a new disc geometry
  35949. * @param id defines the unique ID of the geometry
  35950. * @param scene defines the hosting scene
  35951. * @param radius defines the radius of the disc
  35952. * @param tessellation defines the tesselation factor to apply to the disc
  35953. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35954. * @param mesh defines the hosting mesh (can be null)
  35955. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35956. */
  35957. function DiscGeometry(id, scene,
  35958. /**
  35959. * Defines the radius of the disc
  35960. */
  35961. radius,
  35962. /**
  35963. * Defines the tesselation factor to apply to the disc
  35964. */
  35965. tessellation, canBeRegenerated, mesh,
  35966. /**
  35967. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35968. */
  35969. side) {
  35970. if (mesh === void 0) { mesh = null; }
  35971. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35972. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35973. _this.radius = radius;
  35974. _this.tessellation = tessellation;
  35975. _this.side = side;
  35976. return _this;
  35977. }
  35978. DiscGeometry.prototype._regenerateVertexData = function () {
  35979. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35980. };
  35981. DiscGeometry.prototype.copy = function (id) {
  35982. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35983. };
  35984. return DiscGeometry;
  35985. }(_PrimitiveGeometry));
  35986. BABYLON.DiscGeometry = DiscGeometry;
  35987. /**
  35988. * Creates a new cylinder geometry
  35989. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35990. */
  35991. var CylinderGeometry = /** @class */ (function (_super) {
  35992. __extends(CylinderGeometry, _super);
  35993. /**
  35994. * Creates a new cylinder geometry
  35995. * @param id defines the unique ID of the geometry
  35996. * @param scene defines the hosting scene
  35997. * @param height defines the height of the cylinder
  35998. * @param diameterTop defines the diameter of the cylinder's top cap
  35999. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36000. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36001. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36002. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36003. * @param mesh defines the hosting mesh (can be null)
  36004. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36005. */
  36006. function CylinderGeometry(id, scene,
  36007. /**
  36008. * Defines the height of the cylinder
  36009. */
  36010. height,
  36011. /**
  36012. * Defines the diameter of the cylinder's top cap
  36013. */
  36014. diameterTop,
  36015. /**
  36016. * Defines the diameter of the cylinder's bottom cap
  36017. */
  36018. diameterBottom,
  36019. /**
  36020. * Defines the tessellation factor to apply to the cylinder
  36021. */
  36022. tessellation,
  36023. /**
  36024. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36025. */
  36026. subdivisions, canBeRegenerated, mesh,
  36027. /**
  36028. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36029. */
  36030. side) {
  36031. if (subdivisions === void 0) { subdivisions = 1; }
  36032. if (mesh === void 0) { mesh = null; }
  36033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36034. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36035. _this.height = height;
  36036. _this.diameterTop = diameterTop;
  36037. _this.diameterBottom = diameterBottom;
  36038. _this.tessellation = tessellation;
  36039. _this.subdivisions = subdivisions;
  36040. _this.side = side;
  36041. return _this;
  36042. }
  36043. CylinderGeometry.prototype._regenerateVertexData = function () {
  36044. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36045. };
  36046. CylinderGeometry.prototype.copy = function (id) {
  36047. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36048. };
  36049. CylinderGeometry.prototype.serialize = function () {
  36050. var serializationObject = _super.prototype.serialize.call(this);
  36051. serializationObject.height = this.height;
  36052. serializationObject.diameterTop = this.diameterTop;
  36053. serializationObject.diameterBottom = this.diameterBottom;
  36054. serializationObject.tessellation = this.tessellation;
  36055. return serializationObject;
  36056. };
  36057. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36058. if (scene.getGeometryByID(parsedCylinder.id)) {
  36059. return null; // null since geometry could be something else than a cylinder...
  36060. }
  36061. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36062. if (BABYLON.Tags) {
  36063. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36064. }
  36065. scene.pushGeometry(cylinder, true);
  36066. return cylinder;
  36067. };
  36068. return CylinderGeometry;
  36069. }(_PrimitiveGeometry));
  36070. BABYLON.CylinderGeometry = CylinderGeometry;
  36071. /**
  36072. * Creates a new torus geometry
  36073. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36074. */
  36075. var TorusGeometry = /** @class */ (function (_super) {
  36076. __extends(TorusGeometry, _super);
  36077. /**
  36078. * Creates a new torus geometry
  36079. * @param id defines the unique ID of the geometry
  36080. * @param scene defines the hosting scene
  36081. * @param diameter defines the diameter of the torus
  36082. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36083. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36085. * @param mesh defines the hosting mesh (can be null)
  36086. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36087. */
  36088. function TorusGeometry(id, scene,
  36089. /**
  36090. * Defines the diameter of the torus
  36091. */
  36092. diameter,
  36093. /**
  36094. * Defines the thickness of the torus (ie. internal diameter)
  36095. */
  36096. thickness,
  36097. /**
  36098. * Defines the tesselation factor to apply to the torus
  36099. */
  36100. tessellation, canBeRegenerated, mesh,
  36101. /**
  36102. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36103. */
  36104. side) {
  36105. if (mesh === void 0) { mesh = null; }
  36106. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36107. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36108. _this.diameter = diameter;
  36109. _this.thickness = thickness;
  36110. _this.tessellation = tessellation;
  36111. _this.side = side;
  36112. return _this;
  36113. }
  36114. TorusGeometry.prototype._regenerateVertexData = function () {
  36115. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36116. };
  36117. TorusGeometry.prototype.copy = function (id) {
  36118. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36119. };
  36120. TorusGeometry.prototype.serialize = function () {
  36121. var serializationObject = _super.prototype.serialize.call(this);
  36122. serializationObject.diameter = this.diameter;
  36123. serializationObject.thickness = this.thickness;
  36124. serializationObject.tessellation = this.tessellation;
  36125. return serializationObject;
  36126. };
  36127. TorusGeometry.Parse = function (parsedTorus, scene) {
  36128. if (scene.getGeometryByID(parsedTorus.id)) {
  36129. return null; // null since geometry could be something else than a torus...
  36130. }
  36131. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36132. if (BABYLON.Tags) {
  36133. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36134. }
  36135. scene.pushGeometry(torus, true);
  36136. return torus;
  36137. };
  36138. return TorusGeometry;
  36139. }(_PrimitiveGeometry));
  36140. BABYLON.TorusGeometry = TorusGeometry;
  36141. /**
  36142. * Creates a new ground geometry
  36143. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36144. */
  36145. var GroundGeometry = /** @class */ (function (_super) {
  36146. __extends(GroundGeometry, _super);
  36147. /**
  36148. * Creates a new ground geometry
  36149. * @param id defines the unique ID of the geometry
  36150. * @param scene defines the hosting scene
  36151. * @param width defines the width of the ground
  36152. * @param height defines the height of the ground
  36153. * @param subdivisions defines the subdivisions to apply to the ground
  36154. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36155. * @param mesh defines the hosting mesh (can be null)
  36156. */
  36157. function GroundGeometry(id, scene,
  36158. /**
  36159. * Defines the width of the ground
  36160. */
  36161. width,
  36162. /**
  36163. * Defines the height of the ground
  36164. */
  36165. height,
  36166. /**
  36167. * Defines the subdivisions to apply to the ground
  36168. */
  36169. subdivisions, canBeRegenerated, mesh) {
  36170. if (mesh === void 0) { mesh = null; }
  36171. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36172. _this.width = width;
  36173. _this.height = height;
  36174. _this.subdivisions = subdivisions;
  36175. return _this;
  36176. }
  36177. GroundGeometry.prototype._regenerateVertexData = function () {
  36178. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36179. };
  36180. GroundGeometry.prototype.copy = function (id) {
  36181. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36182. };
  36183. GroundGeometry.prototype.serialize = function () {
  36184. var serializationObject = _super.prototype.serialize.call(this);
  36185. serializationObject.width = this.width;
  36186. serializationObject.height = this.height;
  36187. serializationObject.subdivisions = this.subdivisions;
  36188. return serializationObject;
  36189. };
  36190. GroundGeometry.Parse = function (parsedGround, scene) {
  36191. if (scene.getGeometryByID(parsedGround.id)) {
  36192. return null; // null since geometry could be something else than a ground...
  36193. }
  36194. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36195. if (BABYLON.Tags) {
  36196. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36197. }
  36198. scene.pushGeometry(ground, true);
  36199. return ground;
  36200. };
  36201. return GroundGeometry;
  36202. }(_PrimitiveGeometry));
  36203. BABYLON.GroundGeometry = GroundGeometry;
  36204. /**
  36205. * Creates a tiled ground geometry
  36206. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36207. */
  36208. var TiledGroundGeometry = /** @class */ (function (_super) {
  36209. __extends(TiledGroundGeometry, _super);
  36210. /**
  36211. * Creates a tiled ground geometry
  36212. * @param id defines the unique ID of the geometry
  36213. * @param scene defines the hosting scene
  36214. * @param xmin defines the minimum value on X axis
  36215. * @param zmin defines the minimum value on Z axis
  36216. * @param xmax defines the maximum value on X axis
  36217. * @param zmax defines the maximum value on Z axis
  36218. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36219. * @param precision defines the precision to use when computing the tiles
  36220. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36221. * @param mesh defines the hosting mesh (can be null)
  36222. */
  36223. function TiledGroundGeometry(id, scene,
  36224. /**
  36225. * Defines the minimum value on X axis
  36226. */
  36227. xmin,
  36228. /**
  36229. * Defines the minimum value on Z axis
  36230. */
  36231. zmin,
  36232. /**
  36233. * Defines the maximum value on X axis
  36234. */
  36235. xmax,
  36236. /**
  36237. * Defines the maximum value on Z axis
  36238. */
  36239. zmax,
  36240. /**
  36241. * Defines the subdivisions to apply to the ground
  36242. */
  36243. subdivisions,
  36244. /**
  36245. * Defines the precision to use when computing the tiles
  36246. */
  36247. precision, canBeRegenerated, mesh) {
  36248. if (mesh === void 0) { mesh = null; }
  36249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36250. _this.xmin = xmin;
  36251. _this.zmin = zmin;
  36252. _this.xmax = xmax;
  36253. _this.zmax = zmax;
  36254. _this.subdivisions = subdivisions;
  36255. _this.precision = precision;
  36256. return _this;
  36257. }
  36258. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36259. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36260. };
  36261. TiledGroundGeometry.prototype.copy = function (id) {
  36262. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36263. };
  36264. return TiledGroundGeometry;
  36265. }(_PrimitiveGeometry));
  36266. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36267. /**
  36268. * Creates a plane geometry
  36269. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36270. */
  36271. var PlaneGeometry = /** @class */ (function (_super) {
  36272. __extends(PlaneGeometry, _super);
  36273. /**
  36274. * Creates a plane geometry
  36275. * @param id defines the unique ID of the geometry
  36276. * @param scene defines the hosting scene
  36277. * @param size defines the size of the plane (width === height)
  36278. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36279. * @param mesh defines the hosting mesh (can be null)
  36280. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36281. */
  36282. function PlaneGeometry(id, scene,
  36283. /**
  36284. * Defines the size of the plane (width === height)
  36285. */
  36286. size, canBeRegenerated, mesh,
  36287. /**
  36288. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36289. */
  36290. side) {
  36291. if (mesh === void 0) { mesh = null; }
  36292. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36293. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36294. _this.size = size;
  36295. _this.side = side;
  36296. return _this;
  36297. }
  36298. PlaneGeometry.prototype._regenerateVertexData = function () {
  36299. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36300. };
  36301. PlaneGeometry.prototype.copy = function (id) {
  36302. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36303. };
  36304. PlaneGeometry.prototype.serialize = function () {
  36305. var serializationObject = _super.prototype.serialize.call(this);
  36306. serializationObject.size = this.size;
  36307. return serializationObject;
  36308. };
  36309. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36310. if (scene.getGeometryByID(parsedPlane.id)) {
  36311. return null; // null since geometry could be something else than a ground...
  36312. }
  36313. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36314. if (BABYLON.Tags) {
  36315. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36316. }
  36317. scene.pushGeometry(plane, true);
  36318. return plane;
  36319. };
  36320. return PlaneGeometry;
  36321. }(_PrimitiveGeometry));
  36322. BABYLON.PlaneGeometry = PlaneGeometry;
  36323. /**
  36324. * Creates a torus knot geometry
  36325. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36326. */
  36327. var TorusKnotGeometry = /** @class */ (function (_super) {
  36328. __extends(TorusKnotGeometry, _super);
  36329. /**
  36330. * Creates a torus knot geometry
  36331. * @param id defines the unique ID of the geometry
  36332. * @param scene defines the hosting scene
  36333. * @param radius defines the radius of the torus knot
  36334. * @param tube defines the thickness of the torus knot tube
  36335. * @param radialSegments defines the number of radial segments
  36336. * @param tubularSegments defines the number of tubular segments
  36337. * @param p defines the first number of windings
  36338. * @param q defines the second number of windings
  36339. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36340. * @param mesh defines the hosting mesh (can be null)
  36341. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36342. */
  36343. function TorusKnotGeometry(id, scene,
  36344. /**
  36345. * Defines the radius of the torus knot
  36346. */
  36347. radius,
  36348. /**
  36349. * Defines the thickness of the torus knot tube
  36350. */
  36351. tube,
  36352. /**
  36353. * Defines the number of radial segments
  36354. */
  36355. radialSegments,
  36356. /**
  36357. * Defines the number of tubular segments
  36358. */
  36359. tubularSegments,
  36360. /**
  36361. * Defines the first number of windings
  36362. */
  36363. p,
  36364. /**
  36365. * Defines the second number of windings
  36366. */
  36367. q, canBeRegenerated, mesh,
  36368. /**
  36369. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36370. */
  36371. side) {
  36372. if (mesh === void 0) { mesh = null; }
  36373. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36374. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36375. _this.radius = radius;
  36376. _this.tube = tube;
  36377. _this.radialSegments = radialSegments;
  36378. _this.tubularSegments = tubularSegments;
  36379. _this.p = p;
  36380. _this.q = q;
  36381. _this.side = side;
  36382. return _this;
  36383. }
  36384. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36385. 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 });
  36386. };
  36387. TorusKnotGeometry.prototype.copy = function (id) {
  36388. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36389. };
  36390. TorusKnotGeometry.prototype.serialize = function () {
  36391. var serializationObject = _super.prototype.serialize.call(this);
  36392. serializationObject.radius = this.radius;
  36393. serializationObject.tube = this.tube;
  36394. serializationObject.radialSegments = this.radialSegments;
  36395. serializationObject.tubularSegments = this.tubularSegments;
  36396. serializationObject.p = this.p;
  36397. serializationObject.q = this.q;
  36398. return serializationObject;
  36399. };
  36400. ;
  36401. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36402. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36403. return null; // null since geometry could be something else than a ground...
  36404. }
  36405. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36406. if (BABYLON.Tags) {
  36407. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36408. }
  36409. scene.pushGeometry(torusKnot, true);
  36410. return torusKnot;
  36411. };
  36412. return TorusKnotGeometry;
  36413. }(_PrimitiveGeometry));
  36414. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36415. //}
  36416. })(BABYLON || (BABYLON = {}));
  36417. //# sourceMappingURL=babylon.geometry.js.map
  36418. var BABYLON;
  36419. (function (BABYLON) {
  36420. /**
  36421. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36422. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36423. */
  36424. var PostProcessManager = /** @class */ (function () {
  36425. /**
  36426. * Creates a new instance of @see PostProcess
  36427. * @param scene The scene that the post process is associated with.
  36428. */
  36429. function PostProcessManager(scene) {
  36430. this._vertexBuffers = {};
  36431. this._scene = scene;
  36432. }
  36433. PostProcessManager.prototype._prepareBuffers = function () {
  36434. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36435. return;
  36436. }
  36437. // VBO
  36438. var vertices = [];
  36439. vertices.push(1, 1);
  36440. vertices.push(-1, 1);
  36441. vertices.push(-1, -1);
  36442. vertices.push(1, -1);
  36443. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36444. this._buildIndexBuffer();
  36445. };
  36446. PostProcessManager.prototype._buildIndexBuffer = function () {
  36447. // Indices
  36448. var indices = [];
  36449. indices.push(0);
  36450. indices.push(1);
  36451. indices.push(2);
  36452. indices.push(0);
  36453. indices.push(2);
  36454. indices.push(3);
  36455. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36456. };
  36457. /**
  36458. * Rebuilds the vertex buffers of the manager.
  36459. */
  36460. PostProcessManager.prototype._rebuild = function () {
  36461. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36462. if (!vb) {
  36463. return;
  36464. }
  36465. vb._rebuild();
  36466. this._buildIndexBuffer();
  36467. };
  36468. // Methods
  36469. /**
  36470. * Prepares a frame to be run through a post process.
  36471. * @param sourceTexture The input texture to the post procesess. (default: null)
  36472. * @param postProcesses An array of post processes to be run. (default: null)
  36473. * @returns True if the post processes were able to be run.
  36474. */
  36475. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36476. if (sourceTexture === void 0) { sourceTexture = null; }
  36477. if (postProcesses === void 0) { postProcesses = null; }
  36478. var camera = this._scene.activeCamera;
  36479. if (!camera) {
  36480. return false;
  36481. }
  36482. var postProcesses = postProcesses || camera._postProcesses;
  36483. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36484. return false;
  36485. }
  36486. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36487. return true;
  36488. };
  36489. /**
  36490. * Manually render a set of post processes to a texture.
  36491. * @param postProcesses An array of post processes to be run.
  36492. * @param targetTexture The target texture to render to.
  36493. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36494. */
  36495. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36496. if (targetTexture === void 0) { targetTexture = null; }
  36497. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36498. var engine = this._scene.getEngine();
  36499. for (var index = 0; index < postProcesses.length; index++) {
  36500. if (index < postProcesses.length - 1) {
  36501. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36502. }
  36503. else {
  36504. if (targetTexture) {
  36505. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36506. }
  36507. else {
  36508. engine.restoreDefaultFramebuffer();
  36509. }
  36510. }
  36511. var pp = postProcesses[index];
  36512. var effect = pp.apply();
  36513. if (effect) {
  36514. pp.onBeforeRenderObservable.notifyObservers(effect);
  36515. // VBOs
  36516. this._prepareBuffers();
  36517. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36518. // Draw order
  36519. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36520. pp.onAfterRenderObservable.notifyObservers(effect);
  36521. }
  36522. }
  36523. // Restore depth buffer
  36524. engine.setDepthBuffer(true);
  36525. engine.setDepthWrite(true);
  36526. };
  36527. /**
  36528. * Finalize the result of the output of the postprocesses.
  36529. * @param doNotPresent If true the result will not be displayed to the screen.
  36530. * @param targetTexture The target texture to render to.
  36531. * @param faceIndex The index of the face to bind the target texture to.
  36532. * @param postProcesses The array of post processes to render.
  36533. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36534. */
  36535. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36536. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36537. var camera = this._scene.activeCamera;
  36538. if (!camera) {
  36539. return;
  36540. }
  36541. postProcesses = postProcesses || camera._postProcesses;
  36542. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36543. return;
  36544. }
  36545. var engine = this._scene.getEngine();
  36546. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36547. if (index < len - 1) {
  36548. postProcesses[index + 1].activate(camera, targetTexture);
  36549. }
  36550. else {
  36551. if (targetTexture) {
  36552. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36553. }
  36554. else {
  36555. engine.restoreDefaultFramebuffer();
  36556. }
  36557. }
  36558. if (doNotPresent) {
  36559. break;
  36560. }
  36561. var pp = postProcesses[index];
  36562. var effect = pp.apply();
  36563. if (effect) {
  36564. pp.onBeforeRenderObservable.notifyObservers(effect);
  36565. // VBOs
  36566. this._prepareBuffers();
  36567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36568. // Draw order
  36569. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36570. pp.onAfterRenderObservable.notifyObservers(effect);
  36571. }
  36572. }
  36573. // Restore states
  36574. engine.setDepthBuffer(true);
  36575. engine.setDepthWrite(true);
  36576. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36577. };
  36578. /**
  36579. * Disposes of the post process manager.
  36580. */
  36581. PostProcessManager.prototype.dispose = function () {
  36582. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36583. if (buffer) {
  36584. buffer.dispose();
  36585. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36586. }
  36587. if (this._indexBuffer) {
  36588. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36589. this._indexBuffer = null;
  36590. }
  36591. };
  36592. return PostProcessManager;
  36593. }());
  36594. BABYLON.PostProcessManager = PostProcessManager;
  36595. })(BABYLON || (BABYLON = {}));
  36596. //# sourceMappingURL=babylon.postProcessManager.js.map
  36597. var BABYLON;
  36598. (function (BABYLON) {
  36599. /**
  36600. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36601. */
  36602. var PerformanceMonitor = /** @class */ (function () {
  36603. /**
  36604. * constructor
  36605. * @param frameSampleSize The number of samples required to saturate the sliding window
  36606. */
  36607. function PerformanceMonitor(frameSampleSize) {
  36608. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36609. this._enabled = true;
  36610. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36611. }
  36612. /**
  36613. * Samples current frame
  36614. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36615. */
  36616. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36617. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36618. if (!this._enabled)
  36619. return;
  36620. if (this._lastFrameTimeMs != null) {
  36621. var dt = timeMs - this._lastFrameTimeMs;
  36622. this._rollingFrameTime.add(dt);
  36623. }
  36624. this._lastFrameTimeMs = timeMs;
  36625. };
  36626. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36627. /**
  36628. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36629. * @return Average frame time in milliseconds
  36630. */
  36631. get: function () {
  36632. return this._rollingFrameTime.average;
  36633. },
  36634. enumerable: true,
  36635. configurable: true
  36636. });
  36637. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36638. /**
  36639. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36640. * @return Frame time variance in milliseconds squared
  36641. */
  36642. get: function () {
  36643. return this._rollingFrameTime.variance;
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36649. /**
  36650. * Returns the frame time of the most recent frame
  36651. * @return Frame time in milliseconds
  36652. */
  36653. get: function () {
  36654. return this._rollingFrameTime.history(0);
  36655. },
  36656. enumerable: true,
  36657. configurable: true
  36658. });
  36659. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36660. /**
  36661. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36662. * @return Framerate in frames per second
  36663. */
  36664. get: function () {
  36665. return 1000.0 / this._rollingFrameTime.average;
  36666. },
  36667. enumerable: true,
  36668. configurable: true
  36669. });
  36670. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36671. /**
  36672. * Returns the average framerate in frames per second using the most recent frame time
  36673. * @return Framerate in frames per second
  36674. */
  36675. get: function () {
  36676. var history = this._rollingFrameTime.history(0);
  36677. if (history === 0) {
  36678. return 0;
  36679. }
  36680. return 1000.0 / history;
  36681. },
  36682. enumerable: true,
  36683. configurable: true
  36684. });
  36685. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36686. /**
  36687. * Returns true if enough samples have been taken to completely fill the sliding window
  36688. * @return true if saturated
  36689. */
  36690. get: function () {
  36691. return this._rollingFrameTime.isSaturated();
  36692. },
  36693. enumerable: true,
  36694. configurable: true
  36695. });
  36696. /**
  36697. * Enables contributions to the sliding window sample set
  36698. */
  36699. PerformanceMonitor.prototype.enable = function () {
  36700. this._enabled = true;
  36701. };
  36702. /**
  36703. * Disables contributions to the sliding window sample set
  36704. * Samples will not be interpolated over the disabled period
  36705. */
  36706. PerformanceMonitor.prototype.disable = function () {
  36707. this._enabled = false;
  36708. //clear last sample to avoid interpolating over the disabled period when next enabled
  36709. this._lastFrameTimeMs = null;
  36710. };
  36711. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36712. /**
  36713. * Returns true if sampling is enabled
  36714. * @return true if enabled
  36715. */
  36716. get: function () {
  36717. return this._enabled;
  36718. },
  36719. enumerable: true,
  36720. configurable: true
  36721. });
  36722. /**
  36723. * Resets performance monitor
  36724. */
  36725. PerformanceMonitor.prototype.reset = function () {
  36726. //clear last sample to avoid interpolating over the disabled period when next enabled
  36727. this._lastFrameTimeMs = null;
  36728. //wipe record
  36729. this._rollingFrameTime.reset();
  36730. };
  36731. return PerformanceMonitor;
  36732. }());
  36733. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36734. /**
  36735. * RollingAverage
  36736. *
  36737. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36738. */
  36739. var RollingAverage = /** @class */ (function () {
  36740. /**
  36741. * constructor
  36742. * @param length The number of samples required to saturate the sliding window
  36743. */
  36744. function RollingAverage(length) {
  36745. this._samples = new Array(length);
  36746. this.reset();
  36747. }
  36748. /**
  36749. * Adds a sample to the sample set
  36750. * @param v The sample value
  36751. */
  36752. RollingAverage.prototype.add = function (v) {
  36753. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36754. var delta;
  36755. //we need to check if we've already wrapped round
  36756. if (this.isSaturated()) {
  36757. //remove bottom of stack from mean
  36758. var bottomValue = this._samples[this._pos];
  36759. delta = bottomValue - this.average;
  36760. this.average -= delta / (this._sampleCount - 1);
  36761. this._m2 -= delta * (bottomValue - this.average);
  36762. }
  36763. else {
  36764. this._sampleCount++;
  36765. }
  36766. //add new value to mean
  36767. delta = v - this.average;
  36768. this.average += delta / (this._sampleCount);
  36769. this._m2 += delta * (v - this.average);
  36770. //set the new variance
  36771. this.variance = this._m2 / (this._sampleCount - 1);
  36772. this._samples[this._pos] = v;
  36773. this._pos++;
  36774. this._pos %= this._samples.length; //positive wrap around
  36775. };
  36776. /**
  36777. * Returns previously added values or null if outside of history or outside the sliding window domain
  36778. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36779. * @return Value previously recorded with add() or null if outside of range
  36780. */
  36781. RollingAverage.prototype.history = function (i) {
  36782. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36783. return 0;
  36784. }
  36785. var i0 = this._wrapPosition(this._pos - 1.0);
  36786. return this._samples[this._wrapPosition(i0 - i)];
  36787. };
  36788. /**
  36789. * Returns true if enough samples have been taken to completely fill the sliding window
  36790. * @return true if sample-set saturated
  36791. */
  36792. RollingAverage.prototype.isSaturated = function () {
  36793. return this._sampleCount >= this._samples.length;
  36794. };
  36795. /**
  36796. * Resets the rolling average (equivalent to 0 samples taken so far)
  36797. */
  36798. RollingAverage.prototype.reset = function () {
  36799. this.average = 0;
  36800. this.variance = 0;
  36801. this._sampleCount = 0;
  36802. this._pos = 0;
  36803. this._m2 = 0;
  36804. };
  36805. /**
  36806. * Wraps a value around the sample range boundaries
  36807. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36808. * @return Wrapped position in sample range
  36809. */
  36810. RollingAverage.prototype._wrapPosition = function (i) {
  36811. var max = this._samples.length;
  36812. return ((i % max) + max) % max;
  36813. };
  36814. return RollingAverage;
  36815. }());
  36816. BABYLON.RollingAverage = RollingAverage;
  36817. })(BABYLON || (BABYLON = {}));
  36818. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36819. var BABYLON;
  36820. (function (BABYLON) {
  36821. /**
  36822. * This groups together the common properties used for image processing either in direct forward pass
  36823. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36824. * or not.
  36825. */
  36826. var ImageProcessingConfiguration = /** @class */ (function () {
  36827. function ImageProcessingConfiguration() {
  36828. /**
  36829. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36830. */
  36831. this.colorCurves = new BABYLON.ColorCurves();
  36832. this._colorCurvesEnabled = false;
  36833. this._colorGradingEnabled = false;
  36834. this._colorGradingWithGreenDepth = true;
  36835. this._colorGradingBGR = true;
  36836. this._exposure = 1.0;
  36837. this._toneMappingEnabled = false;
  36838. this._contrast = 1.0;
  36839. /**
  36840. * Vignette stretch size.
  36841. */
  36842. this.vignetteStretch = 0;
  36843. /**
  36844. * Vignette centre X Offset.
  36845. */
  36846. this.vignetteCentreX = 0;
  36847. /**
  36848. * Vignette centre Y Offset.
  36849. */
  36850. this.vignetteCentreY = 0;
  36851. /**
  36852. * Vignette weight or intensity of the vignette effect.
  36853. */
  36854. this.vignetteWeight = 1.5;
  36855. /**
  36856. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36857. * if vignetteEnabled is set to true.
  36858. */
  36859. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36860. /**
  36861. * Camera field of view used by the Vignette effect.
  36862. */
  36863. this.vignetteCameraFov = 0.5;
  36864. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36865. this._vignetteEnabled = false;
  36866. this._applyByPostProcess = false;
  36867. this._isEnabled = true;
  36868. /**
  36869. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36870. * @type {BABYLON.Observable}
  36871. */
  36872. this.onUpdateParameters = new BABYLON.Observable();
  36873. }
  36874. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36875. /**
  36876. * Gets wether the color curves effect is enabled.
  36877. */
  36878. get: function () {
  36879. return this._colorCurvesEnabled;
  36880. },
  36881. /**
  36882. * Sets wether the color curves effect is enabled.
  36883. */
  36884. set: function (value) {
  36885. if (this._colorCurvesEnabled === value) {
  36886. return;
  36887. }
  36888. this._colorCurvesEnabled = value;
  36889. this._updateParameters();
  36890. },
  36891. enumerable: true,
  36892. configurable: true
  36893. });
  36894. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36895. /**
  36896. * Gets wether the color grading effect is enabled.
  36897. */
  36898. get: function () {
  36899. return this._colorGradingEnabled;
  36900. },
  36901. /**
  36902. * Sets wether the color grading effect is enabled.
  36903. */
  36904. set: function (value) {
  36905. if (this._colorGradingEnabled === value) {
  36906. return;
  36907. }
  36908. this._colorGradingEnabled = value;
  36909. this._updateParameters();
  36910. },
  36911. enumerable: true,
  36912. configurable: true
  36913. });
  36914. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36915. /**
  36916. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36917. */
  36918. get: function () {
  36919. return this._colorGradingWithGreenDepth;
  36920. },
  36921. /**
  36922. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36923. */
  36924. set: function (value) {
  36925. if (this._colorGradingWithGreenDepth === value) {
  36926. return;
  36927. }
  36928. this._colorGradingWithGreenDepth = value;
  36929. this._updateParameters();
  36930. },
  36931. enumerable: true,
  36932. configurable: true
  36933. });
  36934. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36935. /**
  36936. * Gets wether the color grading texture contains BGR values.
  36937. */
  36938. get: function () {
  36939. return this._colorGradingBGR;
  36940. },
  36941. /**
  36942. * Sets wether the color grading texture contains BGR values.
  36943. */
  36944. set: function (value) {
  36945. if (this._colorGradingBGR === value) {
  36946. return;
  36947. }
  36948. this._colorGradingBGR = value;
  36949. this._updateParameters();
  36950. },
  36951. enumerable: true,
  36952. configurable: true
  36953. });
  36954. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36955. /**
  36956. * Gets the Exposure used in the effect.
  36957. */
  36958. get: function () {
  36959. return this._exposure;
  36960. },
  36961. /**
  36962. * Sets the Exposure used in the effect.
  36963. */
  36964. set: function (value) {
  36965. if (this._exposure === value) {
  36966. return;
  36967. }
  36968. this._exposure = value;
  36969. this._updateParameters();
  36970. },
  36971. enumerable: true,
  36972. configurable: true
  36973. });
  36974. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36975. /**
  36976. * Gets wether the tone mapping effect is enabled.
  36977. */
  36978. get: function () {
  36979. return this._toneMappingEnabled;
  36980. },
  36981. /**
  36982. * Sets wether the tone mapping effect is enabled.
  36983. */
  36984. set: function (value) {
  36985. if (this._toneMappingEnabled === value) {
  36986. return;
  36987. }
  36988. this._toneMappingEnabled = value;
  36989. this._updateParameters();
  36990. },
  36991. enumerable: true,
  36992. configurable: true
  36993. });
  36994. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36995. /**
  36996. * Gets the contrast used in the effect.
  36997. */
  36998. get: function () {
  36999. return this._contrast;
  37000. },
  37001. /**
  37002. * Sets the contrast used in the effect.
  37003. */
  37004. set: function (value) {
  37005. if (this._contrast === value) {
  37006. return;
  37007. }
  37008. this._contrast = value;
  37009. this._updateParameters();
  37010. },
  37011. enumerable: true,
  37012. configurable: true
  37013. });
  37014. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37015. /**
  37016. * Gets the vignette blend mode allowing different kind of effect.
  37017. */
  37018. get: function () {
  37019. return this._vignetteBlendMode;
  37020. },
  37021. /**
  37022. * Sets the vignette blend mode allowing different kind of effect.
  37023. */
  37024. set: function (value) {
  37025. if (this._vignetteBlendMode === value) {
  37026. return;
  37027. }
  37028. this._vignetteBlendMode = value;
  37029. this._updateParameters();
  37030. },
  37031. enumerable: true,
  37032. configurable: true
  37033. });
  37034. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37035. /**
  37036. * Gets wether the vignette effect is enabled.
  37037. */
  37038. get: function () {
  37039. return this._vignetteEnabled;
  37040. },
  37041. /**
  37042. * Sets wether the vignette effect is enabled.
  37043. */
  37044. set: function (value) {
  37045. if (this._vignetteEnabled === value) {
  37046. return;
  37047. }
  37048. this._vignetteEnabled = value;
  37049. this._updateParameters();
  37050. },
  37051. enumerable: true,
  37052. configurable: true
  37053. });
  37054. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37055. /**
  37056. * Gets wether the image processing is applied through a post process or not.
  37057. */
  37058. get: function () {
  37059. return this._applyByPostProcess;
  37060. },
  37061. /**
  37062. * Sets wether the image processing is applied through a post process or not.
  37063. */
  37064. set: function (value) {
  37065. if (this._applyByPostProcess === value) {
  37066. return;
  37067. }
  37068. this._applyByPostProcess = value;
  37069. this._updateParameters();
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37075. /**
  37076. * Gets wether the image processing is enabled or not.
  37077. */
  37078. get: function () {
  37079. return this._isEnabled;
  37080. },
  37081. /**
  37082. * Sets wether the image processing is enabled or not.
  37083. */
  37084. set: function (value) {
  37085. if (this._isEnabled === value) {
  37086. return;
  37087. }
  37088. this._isEnabled = value;
  37089. this._updateParameters();
  37090. },
  37091. enumerable: true,
  37092. configurable: true
  37093. });
  37094. /**
  37095. * Method called each time the image processing information changes requires to recompile the effect.
  37096. */
  37097. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37098. this.onUpdateParameters.notifyObservers(this);
  37099. };
  37100. ImageProcessingConfiguration.prototype.getClassName = function () {
  37101. return "ImageProcessingConfiguration";
  37102. };
  37103. /**
  37104. * Prepare the list of uniforms associated with the Image Processing effects.
  37105. * @param uniformsList The list of uniforms used in the effect
  37106. * @param defines the list of defines currently in use
  37107. */
  37108. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37109. if (defines.EXPOSURE) {
  37110. uniforms.push("exposureLinear");
  37111. }
  37112. if (defines.CONTRAST) {
  37113. uniforms.push("contrast");
  37114. }
  37115. if (defines.COLORGRADING) {
  37116. uniforms.push("colorTransformSettings");
  37117. }
  37118. if (defines.VIGNETTE) {
  37119. uniforms.push("vInverseScreenSize");
  37120. uniforms.push("vignetteSettings1");
  37121. uniforms.push("vignetteSettings2");
  37122. }
  37123. if (defines.COLORCURVES) {
  37124. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37125. }
  37126. };
  37127. /**
  37128. * Prepare the list of samplers associated with the Image Processing effects.
  37129. * @param uniformsList The list of uniforms used in the effect
  37130. * @param defines the list of defines currently in use
  37131. */
  37132. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37133. if (defines.COLORGRADING) {
  37134. samplersList.push("txColorTransform");
  37135. }
  37136. };
  37137. /**
  37138. * Prepare the list of defines associated to the shader.
  37139. * @param defines the list of defines to complete
  37140. */
  37141. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37142. if (forPostProcess === void 0) { forPostProcess = false; }
  37143. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37144. defines.VIGNETTE = false;
  37145. defines.TONEMAPPING = false;
  37146. defines.CONTRAST = false;
  37147. defines.EXPOSURE = false;
  37148. defines.COLORCURVES = false;
  37149. defines.COLORGRADING = false;
  37150. defines.COLORGRADING3D = false;
  37151. defines.IMAGEPROCESSING = false;
  37152. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37153. return;
  37154. }
  37155. defines.VIGNETTE = this.vignetteEnabled;
  37156. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37157. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37158. defines.TONEMAPPING = this.toneMappingEnabled;
  37159. defines.CONTRAST = (this.contrast !== 1.0);
  37160. defines.EXPOSURE = (this.exposure !== 1.0);
  37161. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37162. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37163. if (defines.COLORGRADING) {
  37164. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37165. }
  37166. else {
  37167. defines.COLORGRADING3D = false;
  37168. }
  37169. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37170. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37171. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37172. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37173. };
  37174. /**
  37175. * Returns true if all the image processing information are ready.
  37176. */
  37177. ImageProcessingConfiguration.prototype.isReady = function () {
  37178. // Color Grading texure can not be none blocking.
  37179. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37180. };
  37181. /**
  37182. * Binds the image processing to the shader.
  37183. * @param effect The effect to bind to
  37184. */
  37185. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37186. if (aspectRatio === void 0) { aspectRatio = 1; }
  37187. // Color Curves
  37188. if (this._colorCurvesEnabled && this.colorCurves) {
  37189. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37190. }
  37191. // Vignette
  37192. if (this._vignetteEnabled) {
  37193. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37194. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37195. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37196. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37197. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37198. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37199. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37200. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37201. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37202. var vignettePower = -2.0 * this.vignetteWeight;
  37203. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37204. }
  37205. // Exposure
  37206. effect.setFloat("exposureLinear", this.exposure);
  37207. // Contrast
  37208. effect.setFloat("contrast", this.contrast);
  37209. // Color transform settings
  37210. if (this.colorGradingTexture) {
  37211. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37212. var textureSize = this.colorGradingTexture.getSize().height;
  37213. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37214. 0.5 / textureSize, // textureOffset
  37215. textureSize, // textureSize
  37216. this.colorGradingTexture.level // weight
  37217. );
  37218. }
  37219. };
  37220. /**
  37221. * Clones the current image processing instance.
  37222. * @return The cloned image processing
  37223. */
  37224. ImageProcessingConfiguration.prototype.clone = function () {
  37225. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37226. };
  37227. /**
  37228. * Serializes the current image processing instance to a json representation.
  37229. * @return a JSON representation
  37230. */
  37231. ImageProcessingConfiguration.prototype.serialize = function () {
  37232. return BABYLON.SerializationHelper.Serialize(this);
  37233. };
  37234. /**
  37235. * Parses the image processing from a json representation.
  37236. * @param source the JSON source to parse
  37237. * @return The parsed image processing
  37238. */
  37239. ImageProcessingConfiguration.Parse = function (source) {
  37240. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37241. };
  37242. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37243. /**
  37244. * Used to apply the vignette as a mix with the pixel color.
  37245. */
  37246. get: function () {
  37247. return this._VIGNETTEMODE_MULTIPLY;
  37248. },
  37249. enumerable: true,
  37250. configurable: true
  37251. });
  37252. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37253. /**
  37254. * Used to apply the vignette as a replacement of the pixel color.
  37255. */
  37256. get: function () {
  37257. return this._VIGNETTEMODE_OPAQUE;
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. // Static constants associated to the image processing.
  37263. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37264. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37265. __decorate([
  37266. BABYLON.serializeAsColorCurves()
  37267. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37268. __decorate([
  37269. BABYLON.serialize()
  37270. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37271. __decorate([
  37272. BABYLON.serializeAsTexture()
  37273. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37274. __decorate([
  37275. BABYLON.serialize()
  37276. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37277. __decorate([
  37278. BABYLON.serialize()
  37279. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37280. __decorate([
  37281. BABYLON.serialize()
  37282. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37283. __decorate([
  37284. BABYLON.serialize()
  37285. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37286. __decorate([
  37287. BABYLON.serialize()
  37288. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37289. __decorate([
  37290. BABYLON.serialize()
  37291. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37292. __decorate([
  37293. BABYLON.serialize()
  37294. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37295. __decorate([
  37296. BABYLON.serialize()
  37297. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37298. __decorate([
  37299. BABYLON.serialize()
  37300. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37301. __decorate([
  37302. BABYLON.serialize()
  37303. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37304. __decorate([
  37305. BABYLON.serializeAsColor4()
  37306. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37307. __decorate([
  37308. BABYLON.serialize()
  37309. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37310. __decorate([
  37311. BABYLON.serialize()
  37312. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37313. __decorate([
  37314. BABYLON.serialize()
  37315. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37316. __decorate([
  37317. BABYLON.serialize()
  37318. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37319. __decorate([
  37320. BABYLON.serialize()
  37321. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37322. return ImageProcessingConfiguration;
  37323. }());
  37324. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37325. })(BABYLON || (BABYLON = {}));
  37326. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37327. var BABYLON;
  37328. (function (BABYLON) {
  37329. /**
  37330. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37331. * It can help converting any input color in a desired output one. This can then be used to create effects
  37332. * from sepia, black and white to sixties or futuristic rendering...
  37333. *
  37334. * The only supported format is currently 3dl.
  37335. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37336. */
  37337. var ColorGradingTexture = /** @class */ (function (_super) {
  37338. __extends(ColorGradingTexture, _super);
  37339. /**
  37340. * Instantiates a ColorGradingTexture from the following parameters.
  37341. *
  37342. * @param url The location of the color gradind data (currently only supporting 3dl)
  37343. * @param scene The scene the texture will be used in
  37344. */
  37345. function ColorGradingTexture(url, scene) {
  37346. var _this = _super.call(this, scene) || this;
  37347. if (!url) {
  37348. return _this;
  37349. }
  37350. _this._engine = scene.getEngine();
  37351. _this._textureMatrix = BABYLON.Matrix.Identity();
  37352. _this.name = url;
  37353. _this.url = url;
  37354. _this.hasAlpha = false;
  37355. _this.isCube = false;
  37356. _this.is3D = _this._engine.webGLVersion > 1;
  37357. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37358. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37359. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37360. _this.anisotropicFilteringLevel = 1;
  37361. _this._texture = _this._getFromCache(url, true);
  37362. if (!_this._texture) {
  37363. if (!scene.useDelayedTextureLoading) {
  37364. _this.loadTexture();
  37365. }
  37366. else {
  37367. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37368. }
  37369. }
  37370. return _this;
  37371. }
  37372. /**
  37373. * Returns the texture matrix used in most of the material.
  37374. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37375. */
  37376. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37377. return this._textureMatrix;
  37378. };
  37379. /**
  37380. * Occurs when the file being loaded is a .3dl LUT file.
  37381. */
  37382. ColorGradingTexture.prototype.load3dlTexture = function () {
  37383. var engine = this._engine;
  37384. var texture;
  37385. if (engine.webGLVersion === 1) {
  37386. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37387. }
  37388. else {
  37389. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37390. }
  37391. this._texture = texture;
  37392. var callback = function (text) {
  37393. if (typeof text !== "string") {
  37394. return;
  37395. }
  37396. var data = null;
  37397. var tempData = null;
  37398. var line;
  37399. var lines = text.split('\n');
  37400. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37401. var maxColor = 0;
  37402. for (var i = 0; i < lines.length; i++) {
  37403. line = lines[i];
  37404. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37405. continue;
  37406. if (line.indexOf('#') === 0)
  37407. continue;
  37408. var words = line.split(" ");
  37409. if (size === 0) {
  37410. // Number of space + one
  37411. size = words.length;
  37412. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37413. tempData = new Float32Array(size * size * size * 4);
  37414. continue;
  37415. }
  37416. if (size != 0) {
  37417. var r = Math.max(parseInt(words[0]), 0);
  37418. var g = Math.max(parseInt(words[1]), 0);
  37419. var b = Math.max(parseInt(words[2]), 0);
  37420. maxColor = Math.max(r, maxColor);
  37421. maxColor = Math.max(g, maxColor);
  37422. maxColor = Math.max(b, maxColor);
  37423. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37424. if (tempData) {
  37425. tempData[pixelStorageIndex + 0] = r;
  37426. tempData[pixelStorageIndex + 1] = g;
  37427. tempData[pixelStorageIndex + 2] = b;
  37428. }
  37429. pixelIndexSlice++;
  37430. if (pixelIndexSlice % size == 0) {
  37431. pixelIndexH++;
  37432. pixelIndexSlice = 0;
  37433. if (pixelIndexH % size == 0) {
  37434. pixelIndexW++;
  37435. pixelIndexH = 0;
  37436. }
  37437. }
  37438. }
  37439. }
  37440. if (tempData && data) {
  37441. for (var i = 0; i < tempData.length; i++) {
  37442. if (i > 0 && (i + 1) % 4 === 0) {
  37443. data[i] = 255;
  37444. }
  37445. else {
  37446. var value = tempData[i];
  37447. data[i] = (value / maxColor * 255);
  37448. }
  37449. }
  37450. }
  37451. if (texture.is3D) {
  37452. texture.updateSize(size, size, size);
  37453. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37454. }
  37455. else {
  37456. texture.updateSize(size * size, size);
  37457. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37458. }
  37459. };
  37460. var scene = this.getScene();
  37461. if (scene) {
  37462. scene._loadFile(this.url, callback);
  37463. }
  37464. else {
  37465. this._engine._loadFile(this.url, callback);
  37466. }
  37467. return this._texture;
  37468. };
  37469. /**
  37470. * Starts the loading process of the texture.
  37471. */
  37472. ColorGradingTexture.prototype.loadTexture = function () {
  37473. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37474. this.load3dlTexture();
  37475. }
  37476. };
  37477. /**
  37478. * Clones the color gradind texture.
  37479. */
  37480. ColorGradingTexture.prototype.clone = function () {
  37481. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37482. // Base texture
  37483. newTexture.level = this.level;
  37484. return newTexture;
  37485. };
  37486. /**
  37487. * Called during delayed load for textures.
  37488. */
  37489. ColorGradingTexture.prototype.delayLoad = function () {
  37490. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37491. return;
  37492. }
  37493. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37494. this._texture = this._getFromCache(this.url, true);
  37495. if (!this._texture) {
  37496. this.loadTexture();
  37497. }
  37498. };
  37499. /**
  37500. * Parses a color grading texture serialized by Babylon.
  37501. * @param parsedTexture The texture information being parsedTexture
  37502. * @param scene The scene to load the texture in
  37503. * @param rootUrl The root url of the data assets to load
  37504. * @return A color gradind texture
  37505. */
  37506. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37507. var texture = null;
  37508. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37509. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37510. texture.name = parsedTexture.name;
  37511. texture.level = parsedTexture.level;
  37512. }
  37513. return texture;
  37514. };
  37515. /**
  37516. * Serializes the LUT texture to json format.
  37517. */
  37518. ColorGradingTexture.prototype.serialize = function () {
  37519. if (!this.name) {
  37520. return null;
  37521. }
  37522. var serializationObject = {};
  37523. serializationObject.name = this.name;
  37524. serializationObject.level = this.level;
  37525. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37526. return serializationObject;
  37527. };
  37528. /**
  37529. * Empty line regex stored for GC.
  37530. */
  37531. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37532. return ColorGradingTexture;
  37533. }(BABYLON.BaseTexture));
  37534. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37535. })(BABYLON || (BABYLON = {}));
  37536. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37537. var BABYLON;
  37538. (function (BABYLON) {
  37539. /**
  37540. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37541. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37542. * 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;
  37543. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37544. */
  37545. var ColorCurves = /** @class */ (function () {
  37546. function ColorCurves() {
  37547. this._dirty = true;
  37548. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37549. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37550. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37551. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37552. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37553. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37554. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37555. this._globalHue = 30;
  37556. this._globalDensity = 0;
  37557. this._globalSaturation = 0;
  37558. this._globalExposure = 0;
  37559. this._highlightsHue = 30;
  37560. this._highlightsDensity = 0;
  37561. this._highlightsSaturation = 0;
  37562. this._highlightsExposure = 0;
  37563. this._midtonesHue = 30;
  37564. this._midtonesDensity = 0;
  37565. this._midtonesSaturation = 0;
  37566. this._midtonesExposure = 0;
  37567. this._shadowsHue = 30;
  37568. this._shadowsDensity = 0;
  37569. this._shadowsSaturation = 0;
  37570. this._shadowsExposure = 0;
  37571. }
  37572. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37573. /**
  37574. * Gets the global Hue value.
  37575. * 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).
  37576. */
  37577. get: function () {
  37578. return this._globalHue;
  37579. },
  37580. /**
  37581. * Sets the global Hue value.
  37582. * 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).
  37583. */
  37584. set: function (value) {
  37585. this._globalHue = value;
  37586. this._dirty = true;
  37587. },
  37588. enumerable: true,
  37589. configurable: true
  37590. });
  37591. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37592. /**
  37593. * Gets the global Density value.
  37594. * 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.
  37595. * Values less than zero provide a filter of opposite hue.
  37596. */
  37597. get: function () {
  37598. return this._globalDensity;
  37599. },
  37600. /**
  37601. * Sets the global Density value.
  37602. * 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.
  37603. * Values less than zero provide a filter of opposite hue.
  37604. */
  37605. set: function (value) {
  37606. this._globalDensity = value;
  37607. this._dirty = true;
  37608. },
  37609. enumerable: true,
  37610. configurable: true
  37611. });
  37612. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37613. /**
  37614. * Gets the global Saturation value.
  37615. * 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.
  37616. */
  37617. get: function () {
  37618. return this._globalSaturation;
  37619. },
  37620. /**
  37621. * Sets the global Saturation value.
  37622. * 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.
  37623. */
  37624. set: function (value) {
  37625. this._globalSaturation = value;
  37626. this._dirty = true;
  37627. },
  37628. enumerable: true,
  37629. configurable: true
  37630. });
  37631. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37632. /**
  37633. * Gets the highlights Hue value.
  37634. * 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).
  37635. */
  37636. get: function () {
  37637. return this._highlightsHue;
  37638. },
  37639. /**
  37640. * Sets the highlights Hue value.
  37641. * 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).
  37642. */
  37643. set: function (value) {
  37644. this._highlightsHue = value;
  37645. this._dirty = true;
  37646. },
  37647. enumerable: true,
  37648. configurable: true
  37649. });
  37650. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37651. /**
  37652. * Gets the highlights Density value.
  37653. * 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.
  37654. * Values less than zero provide a filter of opposite hue.
  37655. */
  37656. get: function () {
  37657. return this._highlightsDensity;
  37658. },
  37659. /**
  37660. * Sets the highlights Density value.
  37661. * 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.
  37662. * Values less than zero provide a filter of opposite hue.
  37663. */
  37664. set: function (value) {
  37665. this._highlightsDensity = value;
  37666. this._dirty = true;
  37667. },
  37668. enumerable: true,
  37669. configurable: true
  37670. });
  37671. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37672. /**
  37673. * Gets the highlights Saturation value.
  37674. * 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.
  37675. */
  37676. get: function () {
  37677. return this._highlightsSaturation;
  37678. },
  37679. /**
  37680. * Sets the highlights Saturation value.
  37681. * 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.
  37682. */
  37683. set: function (value) {
  37684. this._highlightsSaturation = value;
  37685. this._dirty = true;
  37686. },
  37687. enumerable: true,
  37688. configurable: true
  37689. });
  37690. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37691. /**
  37692. * Gets the highlights Exposure value.
  37693. * 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.
  37694. */
  37695. get: function () {
  37696. return this._highlightsExposure;
  37697. },
  37698. /**
  37699. * Sets the highlights Exposure value.
  37700. * 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.
  37701. */
  37702. set: function (value) {
  37703. this._highlightsExposure = value;
  37704. this._dirty = true;
  37705. },
  37706. enumerable: true,
  37707. configurable: true
  37708. });
  37709. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37710. /**
  37711. * Gets the midtones Hue value.
  37712. * 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).
  37713. */
  37714. get: function () {
  37715. return this._midtonesHue;
  37716. },
  37717. /**
  37718. * Sets the midtones Hue value.
  37719. * 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).
  37720. */
  37721. set: function (value) {
  37722. this._midtonesHue = value;
  37723. this._dirty = true;
  37724. },
  37725. enumerable: true,
  37726. configurable: true
  37727. });
  37728. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37729. /**
  37730. * Gets the midtones Density value.
  37731. * 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.
  37732. * Values less than zero provide a filter of opposite hue.
  37733. */
  37734. get: function () {
  37735. return this._midtonesDensity;
  37736. },
  37737. /**
  37738. * Sets the midtones Density value.
  37739. * 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.
  37740. * Values less than zero provide a filter of opposite hue.
  37741. */
  37742. set: function (value) {
  37743. this._midtonesDensity = value;
  37744. this._dirty = true;
  37745. },
  37746. enumerable: true,
  37747. configurable: true
  37748. });
  37749. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37750. /**
  37751. * Gets the midtones Saturation value.
  37752. * 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.
  37753. */
  37754. get: function () {
  37755. return this._midtonesSaturation;
  37756. },
  37757. /**
  37758. * Sets the midtones Saturation value.
  37759. * 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.
  37760. */
  37761. set: function (value) {
  37762. this._midtonesSaturation = value;
  37763. this._dirty = true;
  37764. },
  37765. enumerable: true,
  37766. configurable: true
  37767. });
  37768. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37769. /**
  37770. * Gets the midtones Exposure value.
  37771. * 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.
  37772. */
  37773. get: function () {
  37774. return this._midtonesExposure;
  37775. },
  37776. /**
  37777. * Sets the midtones Exposure value.
  37778. * 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.
  37779. */
  37780. set: function (value) {
  37781. this._midtonesExposure = value;
  37782. this._dirty = true;
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37788. /**
  37789. * Gets the shadows Hue value.
  37790. * 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).
  37791. */
  37792. get: function () {
  37793. return this._shadowsHue;
  37794. },
  37795. /**
  37796. * Sets the shadows Hue value.
  37797. * 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).
  37798. */
  37799. set: function (value) {
  37800. this._shadowsHue = value;
  37801. this._dirty = true;
  37802. },
  37803. enumerable: true,
  37804. configurable: true
  37805. });
  37806. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37807. /**
  37808. * Gets the shadows Density value.
  37809. * 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.
  37810. * Values less than zero provide a filter of opposite hue.
  37811. */
  37812. get: function () {
  37813. return this._shadowsDensity;
  37814. },
  37815. /**
  37816. * Sets the shadows Density value.
  37817. * 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.
  37818. * Values less than zero provide a filter of opposite hue.
  37819. */
  37820. set: function (value) {
  37821. this._shadowsDensity = value;
  37822. this._dirty = true;
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37828. /**
  37829. * Gets the shadows Saturation value.
  37830. * 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.
  37831. */
  37832. get: function () {
  37833. return this._shadowsSaturation;
  37834. },
  37835. /**
  37836. * Sets the shadows Saturation value.
  37837. * 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.
  37838. */
  37839. set: function (value) {
  37840. this._shadowsSaturation = value;
  37841. this._dirty = true;
  37842. },
  37843. enumerable: true,
  37844. configurable: true
  37845. });
  37846. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37847. /**
  37848. * Gets the shadows Exposure value.
  37849. * 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.
  37850. */
  37851. get: function () {
  37852. return this._shadowsExposure;
  37853. },
  37854. /**
  37855. * Sets the shadows Exposure value.
  37856. * 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.
  37857. */
  37858. set: function (value) {
  37859. this._shadowsExposure = value;
  37860. this._dirty = true;
  37861. },
  37862. enumerable: true,
  37863. configurable: true
  37864. });
  37865. ColorCurves.prototype.getClassName = function () {
  37866. return "ColorCurves";
  37867. };
  37868. /**
  37869. * Binds the color curves to the shader.
  37870. * @param colorCurves The color curve to bind
  37871. * @param effect The effect to bind to
  37872. */
  37873. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37874. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37875. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37876. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37877. if (colorCurves._dirty) {
  37878. colorCurves._dirty = false;
  37879. // Fill in global info.
  37880. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37881. // Compute highlights info.
  37882. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37883. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37884. // Compute midtones info.
  37885. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37886. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37887. // Compute shadows info.
  37888. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37889. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37890. // Compute deltas (neutral is midtones).
  37891. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37892. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37893. }
  37894. if (effect) {
  37895. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37896. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37897. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37898. }
  37899. };
  37900. /**
  37901. * Prepare the list of uniforms associated with the ColorCurves effects.
  37902. * @param uniformsList The list of uniforms used in the effect
  37903. */
  37904. ColorCurves.PrepareUniforms = function (uniformsList) {
  37905. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37906. };
  37907. /**
  37908. * Returns color grading data based on a hue, density, saturation and exposure value.
  37909. * @param filterHue The hue of the color filter.
  37910. * @param filterDensity The density of the color filter.
  37911. * @param saturation The saturation.
  37912. * @param exposure The exposure.
  37913. * @param result The result data container.
  37914. */
  37915. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37916. if (hue == null) {
  37917. return;
  37918. }
  37919. hue = ColorCurves.clamp(hue, 0, 360);
  37920. density = ColorCurves.clamp(density, -100, 100);
  37921. saturation = ColorCurves.clamp(saturation, -100, 100);
  37922. exposure = ColorCurves.clamp(exposure, -100, 100);
  37923. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37924. // so that the maximum filter density is only 50% control. This provides fine control
  37925. // for small values and reasonable range.
  37926. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37927. density *= 0.5;
  37928. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37929. if (density < 0) {
  37930. density *= -1;
  37931. hue = (hue + 180) % 360;
  37932. }
  37933. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37934. result.scaleToRef(2, result);
  37935. result.a = 1 + 0.01 * saturation;
  37936. };
  37937. /**
  37938. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37939. * @param value The input slider value in range [-100,100].
  37940. * @returns Adjusted value.
  37941. */
  37942. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37943. value /= 100;
  37944. var x = Math.abs(value);
  37945. x = Math.pow(x, 2);
  37946. if (value < 0) {
  37947. x *= -1;
  37948. }
  37949. x *= 100;
  37950. return x;
  37951. };
  37952. /**
  37953. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37954. * @param hue The hue (H) input.
  37955. * @param saturation The saturation (S) input.
  37956. * @param brightness The brightness (B) input.
  37957. * @result An RGBA color represented as Vector4.
  37958. */
  37959. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37960. var h = ColorCurves.clamp(hue, 0, 360);
  37961. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37962. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37963. if (s === 0) {
  37964. result.r = v;
  37965. result.g = v;
  37966. result.b = v;
  37967. }
  37968. else {
  37969. // sector 0 to 5
  37970. h /= 60;
  37971. var i = Math.floor(h);
  37972. // fractional part of h
  37973. var f = h - i;
  37974. var p = v * (1 - s);
  37975. var q = v * (1 - s * f);
  37976. var t = v * (1 - s * (1 - f));
  37977. switch (i) {
  37978. case 0:
  37979. result.r = v;
  37980. result.g = t;
  37981. result.b = p;
  37982. break;
  37983. case 1:
  37984. result.r = q;
  37985. result.g = v;
  37986. result.b = p;
  37987. break;
  37988. case 2:
  37989. result.r = p;
  37990. result.g = v;
  37991. result.b = t;
  37992. break;
  37993. case 3:
  37994. result.r = p;
  37995. result.g = q;
  37996. result.b = v;
  37997. break;
  37998. case 4:
  37999. result.r = t;
  38000. result.g = p;
  38001. result.b = v;
  38002. break;
  38003. default:// case 5:
  38004. result.r = v;
  38005. result.g = p;
  38006. result.b = q;
  38007. break;
  38008. }
  38009. }
  38010. result.a = 1;
  38011. };
  38012. /**
  38013. * Returns a value clamped between min and max
  38014. * @param value The value to clamp
  38015. * @param min The minimum of value
  38016. * @param max The maximum of value
  38017. * @returns The clamped value.
  38018. */
  38019. ColorCurves.clamp = function (value, min, max) {
  38020. return Math.min(Math.max(value, min), max);
  38021. };
  38022. /**
  38023. * Clones the current color curve instance.
  38024. * @return The cloned curves
  38025. */
  38026. ColorCurves.prototype.clone = function () {
  38027. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38028. };
  38029. /**
  38030. * Serializes the current color curve instance to a json representation.
  38031. * @return a JSON representation
  38032. */
  38033. ColorCurves.prototype.serialize = function () {
  38034. return BABYLON.SerializationHelper.Serialize(this);
  38035. };
  38036. /**
  38037. * Parses the color curve from a json representation.
  38038. * @param source the JSON source to parse
  38039. * @return The parsed curves
  38040. */
  38041. ColorCurves.Parse = function (source) {
  38042. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38043. };
  38044. __decorate([
  38045. BABYLON.serialize()
  38046. ], ColorCurves.prototype, "_globalHue", void 0);
  38047. __decorate([
  38048. BABYLON.serialize()
  38049. ], ColorCurves.prototype, "_globalDensity", void 0);
  38050. __decorate([
  38051. BABYLON.serialize()
  38052. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38053. __decorate([
  38054. BABYLON.serialize()
  38055. ], ColorCurves.prototype, "_globalExposure", void 0);
  38056. __decorate([
  38057. BABYLON.serialize()
  38058. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38059. __decorate([
  38060. BABYLON.serialize()
  38061. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38062. __decorate([
  38063. BABYLON.serialize()
  38064. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38065. __decorate([
  38066. BABYLON.serialize()
  38067. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38068. __decorate([
  38069. BABYLON.serialize()
  38070. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38071. __decorate([
  38072. BABYLON.serialize()
  38073. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38074. __decorate([
  38075. BABYLON.serialize()
  38076. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38077. __decorate([
  38078. BABYLON.serialize()
  38079. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38080. return ColorCurves;
  38081. }());
  38082. BABYLON.ColorCurves = ColorCurves;
  38083. })(BABYLON || (BABYLON = {}));
  38084. //# sourceMappingURL=babylon.colorCurves.js.map
  38085. //# sourceMappingURL=babylon.behavior.js.map
  38086. var BABYLON;
  38087. (function (BABYLON) {
  38088. /**
  38089. * "Static Class" containing the most commonly used helper while dealing with material for
  38090. * rendering purpose.
  38091. *
  38092. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38093. *
  38094. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38095. */
  38096. var MaterialHelper = /** @class */ (function () {
  38097. function MaterialHelper() {
  38098. }
  38099. /**
  38100. * Bind the current view position to an effect.
  38101. * @param effect The effect to be bound
  38102. * @param scene The scene the eyes position is used from
  38103. */
  38104. MaterialHelper.BindEyePosition = function (effect, scene) {
  38105. if (scene._forcedViewPosition) {
  38106. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38107. return;
  38108. }
  38109. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38110. };
  38111. /**
  38112. * Helps preparing the defines values about the UVs in used in the effect.
  38113. * UVs are shared as much as we can accross chanels in the shaders.
  38114. * @param texture The texture we are preparing the UVs for
  38115. * @param defines The defines to update
  38116. * @param key The chanel key "diffuse", "specular"... used in the shader
  38117. */
  38118. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38119. defines._needUVs = true;
  38120. defines[key] = true;
  38121. if (texture.getTextureMatrix().isIdentity(true)) {
  38122. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38123. if (texture.coordinatesIndex === 0) {
  38124. defines["MAINUV1"] = true;
  38125. }
  38126. else {
  38127. defines["MAINUV2"] = true;
  38128. }
  38129. }
  38130. else {
  38131. defines[key + "DIRECTUV"] = 0;
  38132. }
  38133. };
  38134. /**
  38135. * Binds a texture matrix value to its corrsponding uniform
  38136. * @param texture The texture to bind the matrix for
  38137. * @param uniformBuffer The uniform buffer receivin the data
  38138. * @param key The chanel key "diffuse", "specular"... used in the shader
  38139. */
  38140. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38141. var matrix = texture.getTextureMatrix();
  38142. if (!matrix.isIdentity(true)) {
  38143. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38144. }
  38145. };
  38146. /**
  38147. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38148. * @param mesh defines the current mesh
  38149. * @param scene defines the current scene
  38150. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38151. * @param pointsCloud defines if point cloud rendering has to be turned on
  38152. * @param fogEnabled defines if fog has to be turned on
  38153. * @param alphaTest defines if alpha testing has to be turned on
  38154. * @param defines defines the current list of defines
  38155. */
  38156. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38157. if (defines._areMiscDirty) {
  38158. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38159. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38160. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38161. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38162. defines["ALPHATEST"] = alphaTest;
  38163. }
  38164. };
  38165. /**
  38166. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38167. * @param scene defines the current scene
  38168. * @param engine defines the current engine
  38169. * @param defines specifies the list of active defines
  38170. * @param useInstances defines if instances have to be turned on
  38171. * @param useClipPlane defines if clip plane have to be turned on
  38172. */
  38173. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38174. if (useClipPlane === void 0) { useClipPlane = null; }
  38175. var changed = false;
  38176. if (useClipPlane == null) {
  38177. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38178. }
  38179. if (defines["CLIPPLANE"] !== useClipPlane) {
  38180. defines["CLIPPLANE"] = useClipPlane;
  38181. changed = true;
  38182. }
  38183. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38184. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38185. changed = true;
  38186. }
  38187. if (defines["INSTANCES"] !== useInstances) {
  38188. defines["INSTANCES"] = useInstances;
  38189. changed = true;
  38190. }
  38191. if (changed) {
  38192. defines.markAsUnprocessed();
  38193. }
  38194. };
  38195. /**
  38196. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38197. * @param mesh The mesh containing the geometry data we will draw
  38198. * @param defines The defines to update
  38199. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38200. * @param useBones Precise whether bones should be used or not (override mesh info)
  38201. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38202. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38203. * @returns false if defines are considered not dirty and have not been checked
  38204. */
  38205. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38206. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38207. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38208. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38209. return false;
  38210. }
  38211. defines._normals = defines._needNormals;
  38212. defines._uvs = defines._needUVs;
  38213. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38214. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38215. defines["TANGENT"] = true;
  38216. }
  38217. if (defines._needUVs) {
  38218. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38219. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38220. }
  38221. else {
  38222. defines["UV1"] = false;
  38223. defines["UV2"] = false;
  38224. }
  38225. if (useVertexColor) {
  38226. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38227. defines["VERTEXCOLOR"] = hasVertexColors;
  38228. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38229. }
  38230. if (useBones) {
  38231. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38232. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38233. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38234. }
  38235. else {
  38236. defines["NUM_BONE_INFLUENCERS"] = 0;
  38237. defines["BonesPerMesh"] = 0;
  38238. }
  38239. }
  38240. if (useMorphTargets) {
  38241. var manager = mesh.morphTargetManager;
  38242. if (manager) {
  38243. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38244. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38245. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38246. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38247. }
  38248. else {
  38249. defines["MORPHTARGETS_TANGENT"] = false;
  38250. defines["MORPHTARGETS_NORMAL"] = false;
  38251. defines["MORPHTARGETS"] = false;
  38252. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38253. }
  38254. }
  38255. return true;
  38256. };
  38257. /**
  38258. * Prepares the defines related to the light information passed in parameter
  38259. * @param scene The scene we are intending to draw
  38260. * @param mesh The mesh the effect is compiling for
  38261. * @param defines The defines to update
  38262. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38263. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38264. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38265. * @returns true if normals will be required for the rest of the effect
  38266. */
  38267. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38268. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38269. if (disableLighting === void 0) { disableLighting = false; }
  38270. if (!defines._areLightsDirty) {
  38271. return defines._needNormals;
  38272. }
  38273. var lightIndex = 0;
  38274. var needNormals = false;
  38275. var needRebuild = false;
  38276. var lightmapMode = false;
  38277. var shadowEnabled = false;
  38278. var specularEnabled = false;
  38279. if (scene.lightsEnabled && !disableLighting) {
  38280. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38281. var light = _a[_i];
  38282. needNormals = true;
  38283. if (defines["LIGHT" + lightIndex] === undefined) {
  38284. needRebuild = true;
  38285. }
  38286. defines["LIGHT" + lightIndex] = true;
  38287. defines["SPOTLIGHT" + lightIndex] = false;
  38288. defines["HEMILIGHT" + lightIndex] = false;
  38289. defines["POINTLIGHT" + lightIndex] = false;
  38290. defines["DIRLIGHT" + lightIndex] = false;
  38291. var type;
  38292. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38293. type = "SPOTLIGHT" + lightIndex;
  38294. var spotLight = light;
  38295. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38296. }
  38297. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38298. type = "HEMILIGHT" + lightIndex;
  38299. }
  38300. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38301. type = "POINTLIGHT" + lightIndex;
  38302. }
  38303. else {
  38304. type = "DIRLIGHT" + lightIndex;
  38305. }
  38306. defines[type] = true;
  38307. // Specular
  38308. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38309. specularEnabled = true;
  38310. }
  38311. // Shadows
  38312. defines["SHADOW" + lightIndex] = false;
  38313. defines["SHADOWPCF" + lightIndex] = false;
  38314. defines["SHADOWESM" + lightIndex] = false;
  38315. defines["SHADOWCUBE" + lightIndex] = false;
  38316. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38317. var shadowGenerator = light.getShadowGenerator();
  38318. if (shadowGenerator) {
  38319. shadowEnabled = true;
  38320. shadowGenerator.prepareDefines(defines, lightIndex);
  38321. }
  38322. }
  38323. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38324. lightmapMode = true;
  38325. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38326. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38327. }
  38328. else {
  38329. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38330. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38331. }
  38332. lightIndex++;
  38333. if (lightIndex === maxSimultaneousLights)
  38334. break;
  38335. }
  38336. }
  38337. defines["SPECULARTERM"] = specularEnabled;
  38338. defines["SHADOWS"] = shadowEnabled;
  38339. // Resetting all other lights if any
  38340. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38341. if (defines["LIGHT" + index] !== undefined) {
  38342. defines["LIGHT" + index] = false;
  38343. defines["HEMILIGHT" + lightIndex] = false;
  38344. defines["POINTLIGHT" + lightIndex] = false;
  38345. defines["DIRLIGHT" + lightIndex] = false;
  38346. defines["SPOTLIGHT" + lightIndex] = false;
  38347. defines["SHADOW" + lightIndex] = false;
  38348. }
  38349. }
  38350. var caps = scene.getEngine().getCaps();
  38351. if (defines["SHADOWFLOAT"] === undefined) {
  38352. needRebuild = true;
  38353. }
  38354. defines["SHADOWFLOAT"] = shadowEnabled &&
  38355. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38356. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38357. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38358. if (needRebuild) {
  38359. defines.rebuild();
  38360. }
  38361. return needNormals;
  38362. };
  38363. /**
  38364. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38365. * that won t be acctive due to defines being turned off.
  38366. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38367. * @param samplersList The samplers list
  38368. * @param defines The defines helping in the list generation
  38369. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38370. */
  38371. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38372. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38373. var uniformsList;
  38374. var uniformBuffersList = null;
  38375. if (uniformsListOrOptions.uniformsNames) {
  38376. var options = uniformsListOrOptions;
  38377. uniformsList = options.uniformsNames;
  38378. uniformBuffersList = options.uniformBuffersNames;
  38379. samplersList = options.samplers;
  38380. defines = options.defines;
  38381. maxSimultaneousLights = options.maxSimultaneousLights;
  38382. }
  38383. else {
  38384. uniformsList = uniformsListOrOptions;
  38385. if (!samplersList) {
  38386. samplersList = [];
  38387. }
  38388. }
  38389. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38390. if (!defines["LIGHT" + lightIndex]) {
  38391. break;
  38392. }
  38393. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38394. if (uniformBuffersList) {
  38395. uniformBuffersList.push("Light" + lightIndex);
  38396. }
  38397. samplersList.push("shadowSampler" + lightIndex);
  38398. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38399. samplersList.push("projectionLightSampler" + lightIndex);
  38400. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38401. }
  38402. }
  38403. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38404. uniformsList.push("morphTargetInfluences");
  38405. }
  38406. };
  38407. /**
  38408. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38409. * @param defines The defines to update while falling back
  38410. * @param fallbacks The authorized effect fallbacks
  38411. * @param maxSimultaneousLights The maximum number of lights allowed
  38412. * @param rank the current rank of the Effect
  38413. * @returns The newly affected rank
  38414. */
  38415. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38416. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38417. if (rank === void 0) { rank = 0; }
  38418. var lightFallbackRank = 0;
  38419. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38420. if (!defines["LIGHT" + lightIndex]) {
  38421. break;
  38422. }
  38423. if (lightIndex > 0) {
  38424. lightFallbackRank = rank + lightIndex;
  38425. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38426. }
  38427. if (!defines["SHADOWS"]) {
  38428. if (defines["SHADOW" + lightIndex]) {
  38429. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38430. }
  38431. if (defines["SHADOWPCF" + lightIndex]) {
  38432. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38433. }
  38434. if (defines["SHADOWESM" + lightIndex]) {
  38435. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38436. }
  38437. }
  38438. }
  38439. return lightFallbackRank++;
  38440. };
  38441. /**
  38442. * Prepares the list of attributes required for morph targets according to the effect defines.
  38443. * @param attribs The current list of supported attribs
  38444. * @param mesh The mesh to prepare the morph targets attributes for
  38445. * @param defines The current Defines of the effect
  38446. */
  38447. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38448. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38449. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38450. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38451. var manager = mesh.morphTargetManager;
  38452. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38453. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38454. for (var index = 0; index < influencers; index++) {
  38455. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38456. if (normal) {
  38457. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38458. }
  38459. if (tangent) {
  38460. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38461. }
  38462. if (attribs.length > maxAttributesCount) {
  38463. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38464. }
  38465. }
  38466. }
  38467. };
  38468. /**
  38469. * Prepares the list of attributes required for bones according to the effect defines.
  38470. * @param attribs The current list of supported attribs
  38471. * @param mesh The mesh to prepare the bones attributes for
  38472. * @param defines The current Defines of the effect
  38473. * @param fallbacks The current efffect fallback strategy
  38474. */
  38475. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38476. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38477. fallbacks.addCPUSkinningFallback(0, mesh);
  38478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38480. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38481. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38482. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38483. }
  38484. }
  38485. };
  38486. /**
  38487. * Prepares the list of attributes required for instances according to the effect defines.
  38488. * @param attribs The current list of supported attribs
  38489. * @param defines The current Defines of the effect
  38490. */
  38491. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38492. if (defines["INSTANCES"]) {
  38493. attribs.push("world0");
  38494. attribs.push("world1");
  38495. attribs.push("world2");
  38496. attribs.push("world3");
  38497. }
  38498. };
  38499. /**
  38500. * Binds the light shadow information to the effect for the given mesh.
  38501. * @param light The light containing the generator
  38502. * @param scene The scene the lights belongs to
  38503. * @param mesh The mesh we are binding the information to render
  38504. * @param lightIndex The light index in the effect used to render the mesh
  38505. * @param effect The effect we are binding the data to
  38506. */
  38507. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38508. if (light.shadowEnabled && mesh.receiveShadows) {
  38509. var shadowGenerator = light.getShadowGenerator();
  38510. if (shadowGenerator) {
  38511. shadowGenerator.bindShadowLight(lightIndex, effect);
  38512. }
  38513. }
  38514. };
  38515. /**
  38516. * Binds the light information to the effect.
  38517. * @param light The light containing the generator
  38518. * @param effect The effect we are binding the data to
  38519. * @param lightIndex The light index in the effect used to render
  38520. */
  38521. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38522. light.transferToEffect(effect, lightIndex + "");
  38523. };
  38524. /**
  38525. * Binds the lights information from the scene to the effect for the given mesh.
  38526. * @param scene The scene the lights belongs to
  38527. * @param mesh The mesh we are binding the information to render
  38528. * @param effect The effect we are binding the data to
  38529. * @param defines The generated defines for the effect
  38530. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38531. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38532. */
  38533. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38534. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38535. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38536. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38537. for (var i = 0; i < len; i++) {
  38538. var light = mesh._lightSources[i];
  38539. var iAsString = i.toString();
  38540. var scaledIntensity = light.getScaledIntensity();
  38541. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38542. MaterialHelper.BindLightProperties(light, effect, i);
  38543. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38544. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38545. if (defines["SPECULARTERM"]) {
  38546. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38547. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38548. }
  38549. // Shadows
  38550. if (scene.shadowsEnabled) {
  38551. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38552. }
  38553. light._uniformBuffer.update();
  38554. }
  38555. };
  38556. /**
  38557. * Binds the fog information from the scene to the effect for the given mesh.
  38558. * @param scene The scene the lights belongs to
  38559. * @param mesh The mesh we are binding the information to render
  38560. * @param effect The effect we are binding the data to
  38561. */
  38562. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38563. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38564. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38565. effect.setColor3("vFogColor", scene.fogColor);
  38566. }
  38567. };
  38568. /**
  38569. * Binds the bones information from the mesh to the effect.
  38570. * @param mesh The mesh we are binding the information to render
  38571. * @param effect The effect we are binding the data to
  38572. */
  38573. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38574. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38575. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38576. if (matrices && effect) {
  38577. effect.setMatrices("mBones", matrices);
  38578. }
  38579. }
  38580. };
  38581. /**
  38582. * Binds the morph targets information from the mesh to the effect.
  38583. * @param abstractMesh The mesh we are binding the information to render
  38584. * @param effect The effect we are binding the data to
  38585. */
  38586. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38587. var manager = abstractMesh.morphTargetManager;
  38588. if (!abstractMesh || !manager) {
  38589. return;
  38590. }
  38591. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38592. };
  38593. /**
  38594. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38595. * @param defines The generated defines used in the effect
  38596. * @param effect The effect we are binding the data to
  38597. * @param scene The scene we are willing to render with logarithmic scale for
  38598. */
  38599. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38600. if (defines["LOGARITHMICDEPTH"]) {
  38601. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38602. }
  38603. };
  38604. /**
  38605. * Binds the clip plane information from the scene to the effect.
  38606. * @param scene The scene the clip plane information are extracted from
  38607. * @param effect The effect we are binding the data to
  38608. */
  38609. MaterialHelper.BindClipPlane = function (effect, scene) {
  38610. if (scene.clipPlane) {
  38611. var clipPlane = scene.clipPlane;
  38612. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38613. }
  38614. };
  38615. return MaterialHelper;
  38616. }());
  38617. BABYLON.MaterialHelper = MaterialHelper;
  38618. })(BABYLON || (BABYLON = {}));
  38619. //# sourceMappingURL=babylon.materialHelper.js.map
  38620. var BABYLON;
  38621. (function (BABYLON) {
  38622. var PushMaterial = /** @class */ (function (_super) {
  38623. __extends(PushMaterial, _super);
  38624. function PushMaterial(name, scene) {
  38625. var _this = _super.call(this, name, scene) || this;
  38626. _this._normalMatrix = new BABYLON.Matrix();
  38627. _this.storeEffectOnSubMeshes = true;
  38628. return _this;
  38629. }
  38630. PushMaterial.prototype.getEffect = function () {
  38631. return this._activeEffect;
  38632. };
  38633. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38634. if (!mesh) {
  38635. return false;
  38636. }
  38637. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38638. return true;
  38639. }
  38640. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38641. };
  38642. /**
  38643. * Binds the given world matrix to the active effect
  38644. *
  38645. * @param world the matrix to bind
  38646. */
  38647. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38648. this._activeEffect.setMatrix("world", world);
  38649. };
  38650. /**
  38651. * Binds the given normal matrix to the active effect
  38652. *
  38653. * @param normalMatrix the matrix to bind
  38654. */
  38655. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38656. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38657. };
  38658. PushMaterial.prototype.bind = function (world, mesh) {
  38659. if (!mesh) {
  38660. return;
  38661. }
  38662. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38663. };
  38664. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38665. if (effect === void 0) { effect = null; }
  38666. _super.prototype._afterBind.call(this, mesh);
  38667. this.getScene()._cachedEffect = effect;
  38668. };
  38669. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38670. if (visibility === void 0) { visibility = 1; }
  38671. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38672. };
  38673. return PushMaterial;
  38674. }(BABYLON.Material));
  38675. BABYLON.PushMaterial = PushMaterial;
  38676. })(BABYLON || (BABYLON = {}));
  38677. //# sourceMappingURL=babylon.pushMaterial.js.map
  38678. var BABYLON;
  38679. (function (BABYLON) {
  38680. /** @ignore */
  38681. var StandardMaterialDefines = /** @class */ (function (_super) {
  38682. __extends(StandardMaterialDefines, _super);
  38683. function StandardMaterialDefines() {
  38684. var _this = _super.call(this) || this;
  38685. _this.MAINUV1 = false;
  38686. _this.MAINUV2 = false;
  38687. _this.DIFFUSE = false;
  38688. _this.DIFFUSEDIRECTUV = 0;
  38689. _this.AMBIENT = false;
  38690. _this.AMBIENTDIRECTUV = 0;
  38691. _this.OPACITY = false;
  38692. _this.OPACITYDIRECTUV = 0;
  38693. _this.OPACITYRGB = false;
  38694. _this.REFLECTION = false;
  38695. _this.EMISSIVE = false;
  38696. _this.EMISSIVEDIRECTUV = 0;
  38697. _this.SPECULAR = false;
  38698. _this.SPECULARDIRECTUV = 0;
  38699. _this.BUMP = false;
  38700. _this.BUMPDIRECTUV = 0;
  38701. _this.PARALLAX = false;
  38702. _this.PARALLAXOCCLUSION = false;
  38703. _this.SPECULAROVERALPHA = false;
  38704. _this.CLIPPLANE = false;
  38705. _this.ALPHATEST = false;
  38706. _this.DEPTHPREPASS = false;
  38707. _this.ALPHAFROMDIFFUSE = false;
  38708. _this.POINTSIZE = false;
  38709. _this.FOG = false;
  38710. _this.SPECULARTERM = false;
  38711. _this.DIFFUSEFRESNEL = false;
  38712. _this.OPACITYFRESNEL = false;
  38713. _this.REFLECTIONFRESNEL = false;
  38714. _this.REFRACTIONFRESNEL = false;
  38715. _this.EMISSIVEFRESNEL = false;
  38716. _this.FRESNEL = false;
  38717. _this.NORMAL = false;
  38718. _this.UV1 = false;
  38719. _this.UV2 = false;
  38720. _this.VERTEXCOLOR = false;
  38721. _this.VERTEXALPHA = false;
  38722. _this.NUM_BONE_INFLUENCERS = 0;
  38723. _this.BonesPerMesh = 0;
  38724. _this.INSTANCES = false;
  38725. _this.GLOSSINESS = false;
  38726. _this.ROUGHNESS = false;
  38727. _this.EMISSIVEASILLUMINATION = false;
  38728. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38729. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38730. _this.LIGHTMAP = false;
  38731. _this.LIGHTMAPDIRECTUV = 0;
  38732. _this.OBJECTSPACE_NORMALMAP = false;
  38733. _this.USELIGHTMAPASSHADOWMAP = false;
  38734. _this.REFLECTIONMAP_3D = false;
  38735. _this.REFLECTIONMAP_SPHERICAL = false;
  38736. _this.REFLECTIONMAP_PLANAR = false;
  38737. _this.REFLECTIONMAP_CUBIC = false;
  38738. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38739. _this.REFLECTIONMAP_PROJECTION = false;
  38740. _this.REFLECTIONMAP_SKYBOX = false;
  38741. _this.REFLECTIONMAP_EXPLICIT = false;
  38742. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38743. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38744. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38745. _this.INVERTCUBICMAP = false;
  38746. _this.LOGARITHMICDEPTH = false;
  38747. _this.REFRACTION = false;
  38748. _this.REFRACTIONMAP_3D = false;
  38749. _this.REFLECTIONOVERALPHA = false;
  38750. _this.TWOSIDEDLIGHTING = false;
  38751. _this.SHADOWFLOAT = false;
  38752. _this.MORPHTARGETS = false;
  38753. _this.MORPHTARGETS_NORMAL = false;
  38754. _this.MORPHTARGETS_TANGENT = false;
  38755. _this.NUM_MORPH_INFLUENCERS = 0;
  38756. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38757. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38758. _this.IMAGEPROCESSING = false;
  38759. _this.VIGNETTE = false;
  38760. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38761. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38762. _this.TONEMAPPING = false;
  38763. _this.CONTRAST = false;
  38764. _this.COLORCURVES = false;
  38765. _this.COLORGRADING = false;
  38766. _this.COLORGRADING3D = false;
  38767. _this.SAMPLER3DGREENDEPTH = false;
  38768. _this.SAMPLER3DBGRMAP = false;
  38769. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38770. _this.EXPOSURE = false;
  38771. _this.rebuild();
  38772. return _this;
  38773. }
  38774. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38775. var modes = [
  38776. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38777. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38778. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38779. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38780. ];
  38781. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38782. var mode = modes_1[_i];
  38783. this[mode] = (mode === modeToEnable);
  38784. }
  38785. };
  38786. return StandardMaterialDefines;
  38787. }(BABYLON.MaterialDefines));
  38788. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38789. var StandardMaterial = /** @class */ (function (_super) {
  38790. __extends(StandardMaterial, _super);
  38791. function StandardMaterial(name, scene) {
  38792. var _this = _super.call(this, name, scene) || this;
  38793. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38794. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38795. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38796. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38797. _this.specularPower = 64;
  38798. _this._useAlphaFromDiffuseTexture = false;
  38799. _this._useEmissiveAsIllumination = false;
  38800. _this._linkEmissiveWithDiffuse = false;
  38801. _this._useSpecularOverAlpha = false;
  38802. _this._useReflectionOverAlpha = false;
  38803. _this._disableLighting = false;
  38804. _this._useObjectSpaceNormalMap = false;
  38805. _this._useParallax = false;
  38806. _this._useParallaxOcclusion = false;
  38807. _this.parallaxScaleBias = 0.05;
  38808. _this._roughness = 0;
  38809. _this.indexOfRefraction = 0.98;
  38810. _this.invertRefractionY = true;
  38811. _this._useLightmapAsShadowmap = false;
  38812. _this._useReflectionFresnelFromSpecular = false;
  38813. _this._useGlossinessFromSpecularMapAlpha = false;
  38814. _this._maxSimultaneousLights = 4;
  38815. /**
  38816. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38817. */
  38818. _this._invertNormalMapX = false;
  38819. /**
  38820. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38821. */
  38822. _this._invertNormalMapY = false;
  38823. /**
  38824. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38825. */
  38826. _this._twoSidedLighting = false;
  38827. _this._renderTargets = new BABYLON.SmartArray(16);
  38828. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38829. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38830. // Setup the default processing configuration to the scene.
  38831. _this._attachImageProcessingConfiguration(null);
  38832. _this.getRenderTargetTextures = function () {
  38833. _this._renderTargets.reset();
  38834. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38835. _this._renderTargets.push(_this._reflectionTexture);
  38836. }
  38837. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38838. _this._renderTargets.push(_this._refractionTexture);
  38839. }
  38840. return _this._renderTargets;
  38841. };
  38842. return _this;
  38843. }
  38844. ;
  38845. ;
  38846. ;
  38847. ;
  38848. ;
  38849. ;
  38850. ;
  38851. ;
  38852. ;
  38853. ;
  38854. ;
  38855. ;
  38856. ;
  38857. ;
  38858. ;
  38859. ;
  38860. ;
  38861. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38862. /**
  38863. * Gets the image processing configuration used either in this material.
  38864. */
  38865. get: function () {
  38866. return this._imageProcessingConfiguration;
  38867. },
  38868. /**
  38869. * Sets the Default image processing configuration used either in the this material.
  38870. *
  38871. * If sets to null, the scene one is in use.
  38872. */
  38873. set: function (value) {
  38874. this._attachImageProcessingConfiguration(value);
  38875. // Ensure the effect will be rebuilt.
  38876. this._markAllSubMeshesAsTexturesDirty();
  38877. },
  38878. enumerable: true,
  38879. configurable: true
  38880. });
  38881. /**
  38882. * Attaches a new image processing configuration to the Standard Material.
  38883. * @param configuration
  38884. */
  38885. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38886. var _this = this;
  38887. if (configuration === this._imageProcessingConfiguration) {
  38888. return;
  38889. }
  38890. // Detaches observer.
  38891. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38892. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38893. }
  38894. // Pick the scene configuration if needed.
  38895. if (!configuration) {
  38896. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38897. }
  38898. else {
  38899. this._imageProcessingConfiguration = configuration;
  38900. }
  38901. // Attaches observer.
  38902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38903. _this._markAllSubMeshesAsImageProcessingDirty();
  38904. });
  38905. };
  38906. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38907. /**
  38908. * Gets wether the color curves effect is enabled.
  38909. */
  38910. get: function () {
  38911. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38912. },
  38913. /**
  38914. * Sets wether the color curves effect is enabled.
  38915. */
  38916. set: function (value) {
  38917. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38918. },
  38919. enumerable: true,
  38920. configurable: true
  38921. });
  38922. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38923. /**
  38924. * Gets wether the color grading effect is enabled.
  38925. */
  38926. get: function () {
  38927. return this.imageProcessingConfiguration.colorGradingEnabled;
  38928. },
  38929. /**
  38930. * Gets wether the color grading effect is enabled.
  38931. */
  38932. set: function (value) {
  38933. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38934. },
  38935. enumerable: true,
  38936. configurable: true
  38937. });
  38938. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38939. /**
  38940. * Gets wether tonemapping is enabled or not.
  38941. */
  38942. get: function () {
  38943. return this._imageProcessingConfiguration.toneMappingEnabled;
  38944. },
  38945. /**
  38946. * Sets wether tonemapping is enabled or not
  38947. */
  38948. set: function (value) {
  38949. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38950. },
  38951. enumerable: true,
  38952. configurable: true
  38953. });
  38954. ;
  38955. ;
  38956. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38957. /**
  38958. * The camera exposure used on this material.
  38959. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38960. * This corresponds to a photographic exposure.
  38961. */
  38962. get: function () {
  38963. return this._imageProcessingConfiguration.exposure;
  38964. },
  38965. /**
  38966. * The camera exposure used on this material.
  38967. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38968. * This corresponds to a photographic exposure.
  38969. */
  38970. set: function (value) {
  38971. this._imageProcessingConfiguration.exposure = value;
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. ;
  38977. ;
  38978. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38979. /**
  38980. * Gets The camera contrast used on this material.
  38981. */
  38982. get: function () {
  38983. return this._imageProcessingConfiguration.contrast;
  38984. },
  38985. /**
  38986. * Sets The camera contrast used on this material.
  38987. */
  38988. set: function (value) {
  38989. this._imageProcessingConfiguration.contrast = value;
  38990. },
  38991. enumerable: true,
  38992. configurable: true
  38993. });
  38994. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38995. /**
  38996. * Gets the Color Grading 2D Lookup Texture.
  38997. */
  38998. get: function () {
  38999. return this._imageProcessingConfiguration.colorGradingTexture;
  39000. },
  39001. /**
  39002. * Sets the Color Grading 2D Lookup Texture.
  39003. */
  39004. set: function (value) {
  39005. this._imageProcessingConfiguration.colorGradingTexture = value;
  39006. },
  39007. enumerable: true,
  39008. configurable: true
  39009. });
  39010. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39011. /**
  39012. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39013. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39014. * 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;
  39015. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39016. */
  39017. get: function () {
  39018. return this._imageProcessingConfiguration.colorCurves;
  39019. },
  39020. /**
  39021. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39022. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39023. * 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;
  39024. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39025. */
  39026. set: function (value) {
  39027. this._imageProcessingConfiguration.colorCurves = value;
  39028. },
  39029. enumerable: true,
  39030. configurable: true
  39031. });
  39032. StandardMaterial.prototype.getClassName = function () {
  39033. return "StandardMaterial";
  39034. };
  39035. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39036. get: function () {
  39037. return this._useLogarithmicDepth;
  39038. },
  39039. set: function (value) {
  39040. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39041. this._markAllSubMeshesAsMiscDirty();
  39042. },
  39043. enumerable: true,
  39044. configurable: true
  39045. });
  39046. StandardMaterial.prototype.needAlphaBlending = function () {
  39047. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39048. };
  39049. StandardMaterial.prototype.needAlphaTesting = function () {
  39050. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39051. };
  39052. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39053. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39054. };
  39055. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39056. return this._diffuseTexture;
  39057. };
  39058. /**
  39059. * Child classes can use it to update shaders
  39060. */
  39061. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39062. if (useInstances === void 0) { useInstances = false; }
  39063. if (subMesh.effect && this.isFrozen) {
  39064. if (this._wasPreviouslyReady && subMesh.effect) {
  39065. return true;
  39066. }
  39067. }
  39068. if (!subMesh._materialDefines) {
  39069. subMesh._materialDefines = new StandardMaterialDefines();
  39070. }
  39071. var scene = this.getScene();
  39072. var defines = subMesh._materialDefines;
  39073. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39074. if (defines._renderId === scene.getRenderId()) {
  39075. return true;
  39076. }
  39077. }
  39078. var engine = scene.getEngine();
  39079. // Lights
  39080. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39081. // Textures
  39082. if (defines._areTexturesDirty) {
  39083. defines._needUVs = false;
  39084. defines.MAINUV1 = false;
  39085. defines.MAINUV2 = false;
  39086. if (scene.texturesEnabled) {
  39087. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39088. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39089. return false;
  39090. }
  39091. else {
  39092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39093. }
  39094. }
  39095. else {
  39096. defines.DIFFUSE = false;
  39097. }
  39098. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39099. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39100. return false;
  39101. }
  39102. else {
  39103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39104. }
  39105. }
  39106. else {
  39107. defines.AMBIENT = false;
  39108. }
  39109. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39110. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39111. return false;
  39112. }
  39113. else {
  39114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39115. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39116. }
  39117. }
  39118. else {
  39119. defines.OPACITY = false;
  39120. }
  39121. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39122. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39123. return false;
  39124. }
  39125. else {
  39126. defines._needNormals = true;
  39127. defines.REFLECTION = true;
  39128. defines.ROUGHNESS = (this._roughness > 0);
  39129. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39130. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39131. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39132. switch (this._reflectionTexture.coordinatesMode) {
  39133. case BABYLON.Texture.CUBIC_MODE:
  39134. case BABYLON.Texture.INVCUBIC_MODE:
  39135. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39136. break;
  39137. case BABYLON.Texture.EXPLICIT_MODE:
  39138. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39139. break;
  39140. case BABYLON.Texture.PLANAR_MODE:
  39141. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39142. break;
  39143. case BABYLON.Texture.PROJECTION_MODE:
  39144. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39145. break;
  39146. case BABYLON.Texture.SKYBOX_MODE:
  39147. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39148. break;
  39149. case BABYLON.Texture.SPHERICAL_MODE:
  39150. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39151. break;
  39152. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39153. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39154. break;
  39155. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39156. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39157. break;
  39158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39159. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39160. break;
  39161. }
  39162. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39163. }
  39164. }
  39165. else {
  39166. defines.REFLECTION = false;
  39167. }
  39168. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39169. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39170. return false;
  39171. }
  39172. else {
  39173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39174. }
  39175. }
  39176. else {
  39177. defines.EMISSIVE = false;
  39178. }
  39179. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39180. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39181. return false;
  39182. }
  39183. else {
  39184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39185. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39186. }
  39187. }
  39188. else {
  39189. defines.LIGHTMAP = false;
  39190. }
  39191. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39192. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39193. return false;
  39194. }
  39195. else {
  39196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39197. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39198. }
  39199. }
  39200. else {
  39201. defines.SPECULAR = false;
  39202. }
  39203. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39204. // Bump texure can not be not blocking.
  39205. if (!this._bumpTexture.isReady()) {
  39206. return false;
  39207. }
  39208. else {
  39209. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39210. defines.PARALLAX = this._useParallax;
  39211. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39212. }
  39213. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39214. }
  39215. else {
  39216. defines.BUMP = false;
  39217. }
  39218. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39219. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39220. return false;
  39221. }
  39222. else {
  39223. defines._needUVs = true;
  39224. defines.REFRACTION = true;
  39225. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39226. }
  39227. }
  39228. else {
  39229. defines.REFRACTION = false;
  39230. }
  39231. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39232. }
  39233. else {
  39234. defines.DIFFUSE = false;
  39235. defines.AMBIENT = false;
  39236. defines.OPACITY = false;
  39237. defines.REFLECTION = false;
  39238. defines.EMISSIVE = false;
  39239. defines.LIGHTMAP = false;
  39240. defines.BUMP = false;
  39241. defines.REFRACTION = false;
  39242. }
  39243. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39244. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39245. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39246. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39247. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39248. }
  39249. if (defines._areImageProcessingDirty) {
  39250. if (!this._imageProcessingConfiguration.isReady()) {
  39251. return false;
  39252. }
  39253. this._imageProcessingConfiguration.prepareDefines(defines);
  39254. }
  39255. if (defines._areFresnelDirty) {
  39256. if (StandardMaterial.FresnelEnabled) {
  39257. // Fresnel
  39258. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39259. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39260. this._reflectionFresnelParameters) {
  39261. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39262. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39263. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39264. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39265. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39266. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39267. defines._needNormals = true;
  39268. defines.FRESNEL = true;
  39269. }
  39270. }
  39271. else {
  39272. defines.FRESNEL = false;
  39273. }
  39274. }
  39275. // Misc.
  39276. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39277. // Attribs
  39278. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39279. // Values that need to be evaluated on every frame
  39280. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39281. // Get correct effect
  39282. if (defines.isDirty) {
  39283. defines.markAsProcessed();
  39284. scene.resetCachedMaterial();
  39285. // Fallbacks
  39286. var fallbacks = new BABYLON.EffectFallbacks();
  39287. if (defines.REFLECTION) {
  39288. fallbacks.addFallback(0, "REFLECTION");
  39289. }
  39290. if (defines.SPECULAR) {
  39291. fallbacks.addFallback(0, "SPECULAR");
  39292. }
  39293. if (defines.BUMP) {
  39294. fallbacks.addFallback(0, "BUMP");
  39295. }
  39296. if (defines.PARALLAX) {
  39297. fallbacks.addFallback(1, "PARALLAX");
  39298. }
  39299. if (defines.PARALLAXOCCLUSION) {
  39300. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39301. }
  39302. if (defines.SPECULAROVERALPHA) {
  39303. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39304. }
  39305. if (defines.FOG) {
  39306. fallbacks.addFallback(1, "FOG");
  39307. }
  39308. if (defines.POINTSIZE) {
  39309. fallbacks.addFallback(0, "POINTSIZE");
  39310. }
  39311. if (defines.LOGARITHMICDEPTH) {
  39312. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39313. }
  39314. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39315. if (defines.SPECULARTERM) {
  39316. fallbacks.addFallback(0, "SPECULARTERM");
  39317. }
  39318. if (defines.DIFFUSEFRESNEL) {
  39319. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39320. }
  39321. if (defines.OPACITYFRESNEL) {
  39322. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39323. }
  39324. if (defines.REFLECTIONFRESNEL) {
  39325. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39326. }
  39327. if (defines.EMISSIVEFRESNEL) {
  39328. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39329. }
  39330. if (defines.FRESNEL) {
  39331. fallbacks.addFallback(4, "FRESNEL");
  39332. }
  39333. //Attributes
  39334. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39335. if (defines.NORMAL) {
  39336. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39337. }
  39338. if (defines.UV1) {
  39339. attribs.push(BABYLON.VertexBuffer.UVKind);
  39340. }
  39341. if (defines.UV2) {
  39342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39343. }
  39344. if (defines.VERTEXCOLOR) {
  39345. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39346. }
  39347. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39348. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39349. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39350. var shaderName = "default";
  39351. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39352. "vFogInfos", "vFogColor", "pointSize",
  39353. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39354. "mBones",
  39355. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39356. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39357. "vReflectionPosition", "vReflectionSize",
  39358. "logarithmicDepthConstant", "vTangentSpaceParams"
  39359. ];
  39360. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39361. var uniformBuffers = ["Material", "Scene"];
  39362. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39364. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39365. uniformsNames: uniforms,
  39366. uniformBuffersNames: uniformBuffers,
  39367. samplers: samplers,
  39368. defines: defines,
  39369. maxSimultaneousLights: this._maxSimultaneousLights
  39370. });
  39371. if (this.customShaderNameResolve) {
  39372. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39373. }
  39374. var join = defines.toString();
  39375. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39376. attributes: attribs,
  39377. uniformsNames: uniforms,
  39378. uniformBuffersNames: uniformBuffers,
  39379. samplers: samplers,
  39380. defines: join,
  39381. fallbacks: fallbacks,
  39382. onCompiled: this.onCompiled,
  39383. onError: this.onError,
  39384. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39385. }, engine), defines);
  39386. this.buildUniformLayout();
  39387. }
  39388. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39389. return false;
  39390. }
  39391. defines._renderId = scene.getRenderId();
  39392. this._wasPreviouslyReady = true;
  39393. return true;
  39394. };
  39395. StandardMaterial.prototype.buildUniformLayout = function () {
  39396. // Order is important !
  39397. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39398. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39399. this._uniformBuffer.addUniform("opacityParts", 4);
  39400. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39401. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39402. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39403. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39404. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39405. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39406. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39407. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39408. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39409. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39410. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39411. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39412. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39413. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39414. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39415. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39416. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39417. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39418. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39419. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39420. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39421. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39422. this._uniformBuffer.addUniform("specularMatrix", 16);
  39423. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39424. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39425. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39426. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39427. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39428. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39429. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39430. this._uniformBuffer.addUniform("pointSize", 1);
  39431. this._uniformBuffer.create();
  39432. };
  39433. StandardMaterial.prototype.unbind = function () {
  39434. if (this._activeEffect) {
  39435. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39436. this._activeEffect.setTexture("reflection2DSampler", null);
  39437. }
  39438. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39439. this._activeEffect.setTexture("refraction2DSampler", null);
  39440. }
  39441. }
  39442. _super.prototype.unbind.call(this);
  39443. };
  39444. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39445. var scene = this.getScene();
  39446. var defines = subMesh._materialDefines;
  39447. if (!defines) {
  39448. return;
  39449. }
  39450. var effect = subMesh.effect;
  39451. if (!effect) {
  39452. return;
  39453. }
  39454. this._activeEffect = effect;
  39455. // Matrices
  39456. this.bindOnlyWorldMatrix(world);
  39457. // Normal Matrix
  39458. if (defines.OBJECTSPACE_NORMALMAP) {
  39459. world.toNormalMatrix(this._normalMatrix);
  39460. this.bindOnlyNormalMatrix(this._normalMatrix);
  39461. }
  39462. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39463. // Bones
  39464. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39465. if (mustRebind) {
  39466. this._uniformBuffer.bindToEffect(effect, "Material");
  39467. this.bindViewProjection(effect);
  39468. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39469. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39470. // Fresnel
  39471. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39472. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39473. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39474. }
  39475. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39476. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39477. }
  39478. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39479. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39480. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39481. }
  39482. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39483. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39484. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39485. }
  39486. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39487. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39488. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39489. }
  39490. }
  39491. // Textures
  39492. if (scene.texturesEnabled) {
  39493. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39494. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39495. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39496. }
  39497. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39498. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39499. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39500. }
  39501. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39502. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39503. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39504. }
  39505. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39506. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39507. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39508. if (this._reflectionTexture.boundingBoxSize) {
  39509. var cubeTexture = this._reflectionTexture;
  39510. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39511. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39512. }
  39513. }
  39514. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39515. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39516. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39517. }
  39518. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39519. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39520. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39521. }
  39522. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39523. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39524. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39525. }
  39526. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39527. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39528. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39529. if (scene._mirroredCameraPosition) {
  39530. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39531. }
  39532. else {
  39533. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39534. }
  39535. }
  39536. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39537. var depth = 1.0;
  39538. if (!this._refractionTexture.isCube) {
  39539. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39540. if (this._refractionTexture.depth) {
  39541. depth = this._refractionTexture.depth;
  39542. }
  39543. }
  39544. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39545. }
  39546. }
  39547. // Point size
  39548. if (this.pointsCloud) {
  39549. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39550. }
  39551. if (defines.SPECULARTERM) {
  39552. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39553. }
  39554. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39555. // Diffuse
  39556. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39557. }
  39558. // Textures
  39559. if (scene.texturesEnabled) {
  39560. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39561. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39562. }
  39563. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39564. effect.setTexture("ambientSampler", this._ambientTexture);
  39565. }
  39566. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39567. effect.setTexture("opacitySampler", this._opacityTexture);
  39568. }
  39569. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39570. if (this._reflectionTexture.isCube) {
  39571. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39572. }
  39573. else {
  39574. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39575. }
  39576. }
  39577. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39578. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39579. }
  39580. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39581. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39582. }
  39583. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39584. effect.setTexture("specularSampler", this._specularTexture);
  39585. }
  39586. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39587. effect.setTexture("bumpSampler", this._bumpTexture);
  39588. }
  39589. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39590. var depth = 1.0;
  39591. if (this._refractionTexture.isCube) {
  39592. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39593. }
  39594. else {
  39595. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39596. }
  39597. }
  39598. }
  39599. // Clip plane
  39600. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39601. // Colors
  39602. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39603. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39604. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39605. }
  39606. if (mustRebind || !this.isFrozen) {
  39607. // Lights
  39608. if (scene.lightsEnabled && !this._disableLighting) {
  39609. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39610. }
  39611. // View
  39612. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39613. this.bindView(effect);
  39614. }
  39615. // Fog
  39616. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39617. // Morph targets
  39618. if (defines.NUM_MORPH_INFLUENCERS) {
  39619. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39620. }
  39621. // Log. depth
  39622. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39623. // image processing
  39624. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39625. this._imageProcessingConfiguration.bind(this._activeEffect);
  39626. }
  39627. }
  39628. this._uniformBuffer.update();
  39629. this._afterBind(mesh, this._activeEffect);
  39630. };
  39631. StandardMaterial.prototype.getAnimatables = function () {
  39632. var results = [];
  39633. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39634. results.push(this._diffuseTexture);
  39635. }
  39636. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39637. results.push(this._ambientTexture);
  39638. }
  39639. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39640. results.push(this._opacityTexture);
  39641. }
  39642. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39643. results.push(this._reflectionTexture);
  39644. }
  39645. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39646. results.push(this._emissiveTexture);
  39647. }
  39648. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39649. results.push(this._specularTexture);
  39650. }
  39651. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39652. results.push(this._bumpTexture);
  39653. }
  39654. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39655. results.push(this._lightmapTexture);
  39656. }
  39657. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39658. results.push(this._refractionTexture);
  39659. }
  39660. return results;
  39661. };
  39662. StandardMaterial.prototype.getActiveTextures = function () {
  39663. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39664. if (this._diffuseTexture) {
  39665. activeTextures.push(this._diffuseTexture);
  39666. }
  39667. if (this._ambientTexture) {
  39668. activeTextures.push(this._ambientTexture);
  39669. }
  39670. if (this._opacityTexture) {
  39671. activeTextures.push(this._opacityTexture);
  39672. }
  39673. if (this._reflectionTexture) {
  39674. activeTextures.push(this._reflectionTexture);
  39675. }
  39676. if (this._emissiveTexture) {
  39677. activeTextures.push(this._emissiveTexture);
  39678. }
  39679. if (this._specularTexture) {
  39680. activeTextures.push(this._specularTexture);
  39681. }
  39682. if (this._bumpTexture) {
  39683. activeTextures.push(this._bumpTexture);
  39684. }
  39685. if (this._lightmapTexture) {
  39686. activeTextures.push(this._lightmapTexture);
  39687. }
  39688. if (this._refractionTexture) {
  39689. activeTextures.push(this._refractionTexture);
  39690. }
  39691. return activeTextures;
  39692. };
  39693. StandardMaterial.prototype.hasTexture = function (texture) {
  39694. if (_super.prototype.hasTexture.call(this, texture)) {
  39695. return true;
  39696. }
  39697. if (this._diffuseTexture === texture) {
  39698. return true;
  39699. }
  39700. if (this._ambientTexture === texture) {
  39701. return true;
  39702. }
  39703. if (this._opacityTexture === texture) {
  39704. return true;
  39705. }
  39706. if (this._reflectionTexture === texture) {
  39707. return true;
  39708. }
  39709. if (this._emissiveTexture === texture) {
  39710. return true;
  39711. }
  39712. if (this._specularTexture === texture) {
  39713. return true;
  39714. }
  39715. if (this._bumpTexture === texture) {
  39716. return true;
  39717. }
  39718. if (this._lightmapTexture === texture) {
  39719. return true;
  39720. }
  39721. if (this._refractionTexture === texture) {
  39722. return true;
  39723. }
  39724. return false;
  39725. };
  39726. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39727. if (forceDisposeTextures) {
  39728. if (this._diffuseTexture) {
  39729. this._diffuseTexture.dispose();
  39730. }
  39731. if (this._ambientTexture) {
  39732. this._ambientTexture.dispose();
  39733. }
  39734. if (this._opacityTexture) {
  39735. this._opacityTexture.dispose();
  39736. }
  39737. if (this._reflectionTexture) {
  39738. this._reflectionTexture.dispose();
  39739. }
  39740. if (this._emissiveTexture) {
  39741. this._emissiveTexture.dispose();
  39742. }
  39743. if (this._specularTexture) {
  39744. this._specularTexture.dispose();
  39745. }
  39746. if (this._bumpTexture) {
  39747. this._bumpTexture.dispose();
  39748. }
  39749. if (this._lightmapTexture) {
  39750. this._lightmapTexture.dispose();
  39751. }
  39752. if (this._refractionTexture) {
  39753. this._refractionTexture.dispose();
  39754. }
  39755. }
  39756. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39757. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39758. }
  39759. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39760. };
  39761. StandardMaterial.prototype.clone = function (name) {
  39762. var _this = this;
  39763. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39764. result.name = name;
  39765. result.id = name;
  39766. return result;
  39767. };
  39768. StandardMaterial.prototype.serialize = function () {
  39769. return BABYLON.SerializationHelper.Serialize(this);
  39770. };
  39771. // Statics
  39772. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39773. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39774. };
  39775. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39776. get: function () {
  39777. return StandardMaterial._DiffuseTextureEnabled;
  39778. },
  39779. set: function (value) {
  39780. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39781. return;
  39782. }
  39783. StandardMaterial._DiffuseTextureEnabled = value;
  39784. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39785. },
  39786. enumerable: true,
  39787. configurable: true
  39788. });
  39789. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39790. get: function () {
  39791. return StandardMaterial._AmbientTextureEnabled;
  39792. },
  39793. set: function (value) {
  39794. if (StandardMaterial._AmbientTextureEnabled === value) {
  39795. return;
  39796. }
  39797. StandardMaterial._AmbientTextureEnabled = value;
  39798. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39799. },
  39800. enumerable: true,
  39801. configurable: true
  39802. });
  39803. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39804. get: function () {
  39805. return StandardMaterial._OpacityTextureEnabled;
  39806. },
  39807. set: function (value) {
  39808. if (StandardMaterial._OpacityTextureEnabled === value) {
  39809. return;
  39810. }
  39811. StandardMaterial._OpacityTextureEnabled = value;
  39812. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39818. get: function () {
  39819. return StandardMaterial._ReflectionTextureEnabled;
  39820. },
  39821. set: function (value) {
  39822. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39823. return;
  39824. }
  39825. StandardMaterial._ReflectionTextureEnabled = value;
  39826. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39832. get: function () {
  39833. return StandardMaterial._EmissiveTextureEnabled;
  39834. },
  39835. set: function (value) {
  39836. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39837. return;
  39838. }
  39839. StandardMaterial._EmissiveTextureEnabled = value;
  39840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39841. },
  39842. enumerable: true,
  39843. configurable: true
  39844. });
  39845. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39846. get: function () {
  39847. return StandardMaterial._SpecularTextureEnabled;
  39848. },
  39849. set: function (value) {
  39850. if (StandardMaterial._SpecularTextureEnabled === value) {
  39851. return;
  39852. }
  39853. StandardMaterial._SpecularTextureEnabled = value;
  39854. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39855. },
  39856. enumerable: true,
  39857. configurable: true
  39858. });
  39859. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39860. get: function () {
  39861. return StandardMaterial._BumpTextureEnabled;
  39862. },
  39863. set: function (value) {
  39864. if (StandardMaterial._BumpTextureEnabled === value) {
  39865. return;
  39866. }
  39867. StandardMaterial._BumpTextureEnabled = value;
  39868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39874. get: function () {
  39875. return StandardMaterial._LightmapTextureEnabled;
  39876. },
  39877. set: function (value) {
  39878. if (StandardMaterial._LightmapTextureEnabled === value) {
  39879. return;
  39880. }
  39881. StandardMaterial._LightmapTextureEnabled = value;
  39882. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39888. get: function () {
  39889. return StandardMaterial._RefractionTextureEnabled;
  39890. },
  39891. set: function (value) {
  39892. if (StandardMaterial._RefractionTextureEnabled === value) {
  39893. return;
  39894. }
  39895. StandardMaterial._RefractionTextureEnabled = value;
  39896. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39902. get: function () {
  39903. return StandardMaterial._ColorGradingTextureEnabled;
  39904. },
  39905. set: function (value) {
  39906. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39907. return;
  39908. }
  39909. StandardMaterial._ColorGradingTextureEnabled = value;
  39910. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39911. },
  39912. enumerable: true,
  39913. configurable: true
  39914. });
  39915. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39916. get: function () {
  39917. return StandardMaterial._FresnelEnabled;
  39918. },
  39919. set: function (value) {
  39920. if (StandardMaterial._FresnelEnabled === value) {
  39921. return;
  39922. }
  39923. StandardMaterial._FresnelEnabled = value;
  39924. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39925. },
  39926. enumerable: true,
  39927. configurable: true
  39928. });
  39929. // Flags used to enable or disable a type of texture for all Standard Materials
  39930. StandardMaterial._DiffuseTextureEnabled = true;
  39931. StandardMaterial._AmbientTextureEnabled = true;
  39932. StandardMaterial._OpacityTextureEnabled = true;
  39933. StandardMaterial._ReflectionTextureEnabled = true;
  39934. StandardMaterial._EmissiveTextureEnabled = true;
  39935. StandardMaterial._SpecularTextureEnabled = true;
  39936. StandardMaterial._BumpTextureEnabled = true;
  39937. StandardMaterial._LightmapTextureEnabled = true;
  39938. StandardMaterial._RefractionTextureEnabled = true;
  39939. StandardMaterial._ColorGradingTextureEnabled = true;
  39940. StandardMaterial._FresnelEnabled = true;
  39941. __decorate([
  39942. BABYLON.serializeAsTexture("diffuseTexture")
  39943. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39944. __decorate([
  39945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39946. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39947. __decorate([
  39948. BABYLON.serializeAsTexture("ambientTexture")
  39949. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39950. __decorate([
  39951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39952. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39953. __decorate([
  39954. BABYLON.serializeAsTexture("opacityTexture")
  39955. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39956. __decorate([
  39957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39958. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39959. __decorate([
  39960. BABYLON.serializeAsTexture("reflectionTexture")
  39961. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39962. __decorate([
  39963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39964. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39965. __decorate([
  39966. BABYLON.serializeAsTexture("emissiveTexture")
  39967. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39968. __decorate([
  39969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39970. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39971. __decorate([
  39972. BABYLON.serializeAsTexture("specularTexture")
  39973. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39974. __decorate([
  39975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39976. ], StandardMaterial.prototype, "specularTexture", void 0);
  39977. __decorate([
  39978. BABYLON.serializeAsTexture("bumpTexture")
  39979. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39980. __decorate([
  39981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39982. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39983. __decorate([
  39984. BABYLON.serializeAsTexture("lightmapTexture")
  39985. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39986. __decorate([
  39987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39988. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39989. __decorate([
  39990. BABYLON.serializeAsTexture("refractionTexture")
  39991. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39992. __decorate([
  39993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39994. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39995. __decorate([
  39996. BABYLON.serializeAsColor3("ambient")
  39997. ], StandardMaterial.prototype, "ambientColor", void 0);
  39998. __decorate([
  39999. BABYLON.serializeAsColor3("diffuse")
  40000. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40001. __decorate([
  40002. BABYLON.serializeAsColor3("specular")
  40003. ], StandardMaterial.prototype, "specularColor", void 0);
  40004. __decorate([
  40005. BABYLON.serializeAsColor3("emissive")
  40006. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40007. __decorate([
  40008. BABYLON.serialize()
  40009. ], StandardMaterial.prototype, "specularPower", void 0);
  40010. __decorate([
  40011. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40012. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40013. __decorate([
  40014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40015. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40016. __decorate([
  40017. BABYLON.serialize("useEmissiveAsIllumination")
  40018. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40019. __decorate([
  40020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40021. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40022. __decorate([
  40023. BABYLON.serialize("linkEmissiveWithDiffuse")
  40024. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40025. __decorate([
  40026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40027. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40028. __decorate([
  40029. BABYLON.serialize("useSpecularOverAlpha")
  40030. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40031. __decorate([
  40032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40033. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40034. __decorate([
  40035. BABYLON.serialize("useReflectionOverAlpha")
  40036. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40037. __decorate([
  40038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40039. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40040. __decorate([
  40041. BABYLON.serialize("disableLighting")
  40042. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40043. __decorate([
  40044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40045. ], StandardMaterial.prototype, "disableLighting", void 0);
  40046. __decorate([
  40047. BABYLON.serialize("useObjectSpaceNormalMap")
  40048. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40049. __decorate([
  40050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40051. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40052. __decorate([
  40053. BABYLON.serialize("useParallax")
  40054. ], StandardMaterial.prototype, "_useParallax", void 0);
  40055. __decorate([
  40056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40057. ], StandardMaterial.prototype, "useParallax", void 0);
  40058. __decorate([
  40059. BABYLON.serialize("useParallaxOcclusion")
  40060. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40061. __decorate([
  40062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40063. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40064. __decorate([
  40065. BABYLON.serialize()
  40066. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40067. __decorate([
  40068. BABYLON.serialize("roughness")
  40069. ], StandardMaterial.prototype, "_roughness", void 0);
  40070. __decorate([
  40071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40072. ], StandardMaterial.prototype, "roughness", void 0);
  40073. __decorate([
  40074. BABYLON.serialize()
  40075. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40076. __decorate([
  40077. BABYLON.serialize()
  40078. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40079. __decorate([
  40080. BABYLON.serialize("useLightmapAsShadowmap")
  40081. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40082. __decorate([
  40083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40084. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40085. __decorate([
  40086. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40087. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40088. __decorate([
  40089. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40090. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40091. __decorate([
  40092. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40093. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40094. __decorate([
  40095. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40096. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40097. __decorate([
  40098. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40099. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40100. __decorate([
  40101. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40102. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40103. __decorate([
  40104. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40105. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40106. __decorate([
  40107. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40108. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40109. __decorate([
  40110. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40111. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40112. __decorate([
  40113. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40114. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40115. __decorate([
  40116. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40117. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40118. __decorate([
  40119. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40120. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40121. __decorate([
  40122. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40123. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40124. __decorate([
  40125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40126. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40127. __decorate([
  40128. BABYLON.serialize("maxSimultaneousLights")
  40129. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40130. __decorate([
  40131. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40132. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40133. __decorate([
  40134. BABYLON.serialize("invertNormalMapX")
  40135. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40136. __decorate([
  40137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40138. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40139. __decorate([
  40140. BABYLON.serialize("invertNormalMapY")
  40141. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40142. __decorate([
  40143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40144. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40145. __decorate([
  40146. BABYLON.serialize("twoSidedLighting")
  40147. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40148. __decorate([
  40149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40150. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40151. __decorate([
  40152. BABYLON.serialize()
  40153. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40154. return StandardMaterial;
  40155. }(BABYLON.PushMaterial));
  40156. BABYLON.StandardMaterial = StandardMaterial;
  40157. })(BABYLON || (BABYLON = {}));
  40158. //# sourceMappingURL=babylon.standardMaterial.js.map
  40159. var BABYLON;
  40160. (function (BABYLON) {
  40161. /**
  40162. * Manages the defines for the PBR Material.
  40163. */
  40164. var PBRMaterialDefines = /** @class */ (function (_super) {
  40165. __extends(PBRMaterialDefines, _super);
  40166. /**
  40167. * Initializes the PBR Material defines.
  40168. */
  40169. function PBRMaterialDefines() {
  40170. var _this = _super.call(this) || this;
  40171. _this.PBR = true;
  40172. _this.MAINUV1 = false;
  40173. _this.MAINUV2 = false;
  40174. _this.UV1 = false;
  40175. _this.UV2 = false;
  40176. _this.ALBEDO = false;
  40177. _this.ALBEDODIRECTUV = 0;
  40178. _this.VERTEXCOLOR = false;
  40179. _this.AMBIENT = false;
  40180. _this.AMBIENTDIRECTUV = 0;
  40181. _this.AMBIENTINGRAYSCALE = false;
  40182. _this.OPACITY = false;
  40183. _this.VERTEXALPHA = false;
  40184. _this.OPACITYDIRECTUV = 0;
  40185. _this.OPACITYRGB = false;
  40186. _this.ALPHATEST = false;
  40187. _this.DEPTHPREPASS = false;
  40188. _this.ALPHABLEND = false;
  40189. _this.ALPHAFROMALBEDO = false;
  40190. _this.ALPHATESTVALUE = 0.5;
  40191. _this.SPECULAROVERALPHA = false;
  40192. _this.RADIANCEOVERALPHA = false;
  40193. _this.ALPHAFRESNEL = false;
  40194. _this.LINEARALPHAFRESNEL = false;
  40195. _this.PREMULTIPLYALPHA = false;
  40196. _this.EMISSIVE = false;
  40197. _this.EMISSIVEDIRECTUV = 0;
  40198. _this.REFLECTIVITY = false;
  40199. _this.REFLECTIVITYDIRECTUV = 0;
  40200. _this.SPECULARTERM = false;
  40201. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40202. _this.MICROSURFACEAUTOMATIC = false;
  40203. _this.LODBASEDMICROSFURACE = false;
  40204. _this.MICROSURFACEMAP = false;
  40205. _this.MICROSURFACEMAPDIRECTUV = 0;
  40206. _this.METALLICWORKFLOW = false;
  40207. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40208. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40209. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40210. _this.AOSTOREINMETALMAPRED = false;
  40211. _this.ENVIRONMENTBRDF = false;
  40212. _this.NORMAL = false;
  40213. _this.TANGENT = false;
  40214. _this.BUMP = false;
  40215. _this.BUMPDIRECTUV = 0;
  40216. _this.OBJECTSPACE_NORMALMAP = false;
  40217. _this.PARALLAX = false;
  40218. _this.PARALLAXOCCLUSION = false;
  40219. _this.NORMALXYSCALE = true;
  40220. _this.LIGHTMAP = false;
  40221. _this.LIGHTMAPDIRECTUV = 0;
  40222. _this.USELIGHTMAPASSHADOWMAP = false;
  40223. _this.REFLECTION = false;
  40224. _this.REFLECTIONMAP_3D = false;
  40225. _this.REFLECTIONMAP_SPHERICAL = false;
  40226. _this.REFLECTIONMAP_PLANAR = false;
  40227. _this.REFLECTIONMAP_CUBIC = false;
  40228. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40229. _this.REFLECTIONMAP_PROJECTION = false;
  40230. _this.REFLECTIONMAP_SKYBOX = false;
  40231. _this.REFLECTIONMAP_EXPLICIT = false;
  40232. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40233. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40234. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40235. _this.INVERTCUBICMAP = false;
  40236. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40237. _this.USESPHERICALINVERTEX = false;
  40238. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40239. _this.LODINREFLECTIONALPHA = false;
  40240. _this.GAMMAREFLECTION = false;
  40241. _this.RADIANCEOCCLUSION = false;
  40242. _this.HORIZONOCCLUSION = false;
  40243. _this.REFRACTION = false;
  40244. _this.REFRACTIONMAP_3D = false;
  40245. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40246. _this.LODINREFRACTIONALPHA = false;
  40247. _this.GAMMAREFRACTION = false;
  40248. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40249. _this.INSTANCES = false;
  40250. _this.NUM_BONE_INFLUENCERS = 0;
  40251. _this.BonesPerMesh = 0;
  40252. _this.NONUNIFORMSCALING = false;
  40253. _this.MORPHTARGETS = false;
  40254. _this.MORPHTARGETS_NORMAL = false;
  40255. _this.MORPHTARGETS_TANGENT = false;
  40256. _this.NUM_MORPH_INFLUENCERS = 0;
  40257. _this.IMAGEPROCESSING = false;
  40258. _this.VIGNETTE = false;
  40259. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40260. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40261. _this.TONEMAPPING = false;
  40262. _this.CONTRAST = false;
  40263. _this.COLORCURVES = false;
  40264. _this.COLORGRADING = false;
  40265. _this.COLORGRADING3D = false;
  40266. _this.SAMPLER3DGREENDEPTH = false;
  40267. _this.SAMPLER3DBGRMAP = false;
  40268. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40269. _this.EXPOSURE = false;
  40270. _this.USEPHYSICALLIGHTFALLOFF = false;
  40271. _this.TWOSIDEDLIGHTING = false;
  40272. _this.SHADOWFLOAT = false;
  40273. _this.CLIPPLANE = false;
  40274. _this.POINTSIZE = false;
  40275. _this.FOG = false;
  40276. _this.LOGARITHMICDEPTH = false;
  40277. _this.FORCENORMALFORWARD = false;
  40278. _this.rebuild();
  40279. return _this;
  40280. }
  40281. /**
  40282. * Resets the PBR Material defines.
  40283. */
  40284. PBRMaterialDefines.prototype.reset = function () {
  40285. _super.prototype.reset.call(this);
  40286. this.ALPHATESTVALUE = 0.5;
  40287. this.PBR = true;
  40288. };
  40289. return PBRMaterialDefines;
  40290. }(BABYLON.MaterialDefines));
  40291. /**
  40292. * The Physically based material base class of BJS.
  40293. *
  40294. * This offers the main features of a standard PBR material.
  40295. * For more information, please refer to the documentation :
  40296. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40297. */
  40298. var PBRBaseMaterial = /** @class */ (function (_super) {
  40299. __extends(PBRBaseMaterial, _super);
  40300. /**
  40301. * Instantiates a new PBRMaterial instance.
  40302. *
  40303. * @param name The material name
  40304. * @param scene The scene the material will be use in.
  40305. */
  40306. function PBRBaseMaterial(name, scene) {
  40307. var _this = _super.call(this, name, scene) || this;
  40308. /**
  40309. * Intensity of the direct lights e.g. the four lights available in your scene.
  40310. * This impacts both the direct diffuse and specular highlights.
  40311. */
  40312. _this._directIntensity = 1.0;
  40313. /**
  40314. * Intensity of the emissive part of the material.
  40315. * This helps controlling the emissive effect without modifying the emissive color.
  40316. */
  40317. _this._emissiveIntensity = 1.0;
  40318. /**
  40319. * Intensity of the environment e.g. how much the environment will light the object
  40320. * either through harmonics for rough material or through the refelction for shiny ones.
  40321. */
  40322. _this._environmentIntensity = 1.0;
  40323. /**
  40324. * This is a special control allowing the reduction of the specular highlights coming from the
  40325. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40326. */
  40327. _this._specularIntensity = 1.0;
  40328. /**
  40329. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40330. */
  40331. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40332. /**
  40333. * Debug Control allowing disabling the bump map on this material.
  40334. */
  40335. _this._disableBumpMap = false;
  40336. /**
  40337. * AKA Occlusion Texture Intensity in other nomenclature.
  40338. */
  40339. _this._ambientTextureStrength = 1.0;
  40340. /**
  40341. * The color of a material in ambient lighting.
  40342. */
  40343. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40344. /**
  40345. * AKA Diffuse Color in other nomenclature.
  40346. */
  40347. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40348. /**
  40349. * AKA Specular Color in other nomenclature.
  40350. */
  40351. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40352. /**
  40353. * The color applied when light is reflected from a material.
  40354. */
  40355. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40356. /**
  40357. * The color applied when light is emitted from a material.
  40358. */
  40359. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40360. /**
  40361. * AKA Glossiness in other nomenclature.
  40362. */
  40363. _this._microSurface = 0.9;
  40364. /**
  40365. * source material index of refraction (IOR)' / 'destination material IOR.
  40366. */
  40367. _this._indexOfRefraction = 0.66;
  40368. /**
  40369. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40370. */
  40371. _this._invertRefractionY = false;
  40372. /**
  40373. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40374. * Materials half opaque for instance using refraction could benefit from this control.
  40375. */
  40376. _this._linkRefractionWithTransparency = false;
  40377. /**
  40378. * Specifies that the material will use the light map as a show map.
  40379. */
  40380. _this._useLightmapAsShadowmap = false;
  40381. /**
  40382. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40383. * makes the reflect vector face the model (under horizon).
  40384. */
  40385. _this._useHorizonOcclusion = true;
  40386. /**
  40387. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40388. * too much the area relying on ambient texture to define their ambient occlusion.
  40389. */
  40390. _this._useRadianceOcclusion = true;
  40391. /**
  40392. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40393. */
  40394. _this._useAlphaFromAlbedoTexture = false;
  40395. /**
  40396. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40397. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40398. */
  40399. _this._useSpecularOverAlpha = true;
  40400. /**
  40401. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40402. */
  40403. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40404. /**
  40405. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40406. */
  40407. _this._useRoughnessFromMetallicTextureAlpha = true;
  40408. /**
  40409. * Specifies if the metallic texture contains the roughness information in its green channel.
  40410. */
  40411. _this._useRoughnessFromMetallicTextureGreen = false;
  40412. /**
  40413. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40414. */
  40415. _this._useMetallnessFromMetallicTextureBlue = false;
  40416. /**
  40417. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40418. */
  40419. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40420. /**
  40421. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40422. */
  40423. _this._useAmbientInGrayScale = false;
  40424. /**
  40425. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40426. * The material will try to infer what glossiness each pixel should be.
  40427. */
  40428. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40429. /**
  40430. * BJS is using an harcoded light falloff based on a manually sets up range.
  40431. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40432. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40433. */
  40434. _this._usePhysicalLightFalloff = true;
  40435. /**
  40436. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40437. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40438. */
  40439. _this._useRadianceOverAlpha = true;
  40440. /**
  40441. * Allows using an object space normal map (instead of tangent space).
  40442. */
  40443. _this._useObjectSpaceNormalMap = false;
  40444. /**
  40445. * Allows using the bump map in parallax mode.
  40446. */
  40447. _this._useParallax = false;
  40448. /**
  40449. * Allows using the bump map in parallax occlusion mode.
  40450. */
  40451. _this._useParallaxOcclusion = false;
  40452. /**
  40453. * Controls the scale bias of the parallax mode.
  40454. */
  40455. _this._parallaxScaleBias = 0.05;
  40456. /**
  40457. * If sets to true, disables all the lights affecting the material.
  40458. */
  40459. _this._disableLighting = false;
  40460. /**
  40461. * Number of Simultaneous lights allowed on the material.
  40462. */
  40463. _this._maxSimultaneousLights = 4;
  40464. /**
  40465. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40466. */
  40467. _this._invertNormalMapX = false;
  40468. /**
  40469. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40470. */
  40471. _this._invertNormalMapY = false;
  40472. /**
  40473. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40474. */
  40475. _this._twoSidedLighting = false;
  40476. /**
  40477. * Defines the alpha limits in alpha test mode.
  40478. */
  40479. _this._alphaCutOff = 0.4;
  40480. /**
  40481. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40482. */
  40483. _this._forceAlphaTest = false;
  40484. /**
  40485. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40486. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40487. */
  40488. _this._useAlphaFresnel = false;
  40489. /**
  40490. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40491. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40492. */
  40493. _this._useLinearAlphaFresnel = false;
  40494. /**
  40495. * The transparency mode of the material.
  40496. */
  40497. _this._transparencyMode = null;
  40498. /**
  40499. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40500. * from cos thetav and roughness:
  40501. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40502. */
  40503. _this._environmentBRDFTexture = null;
  40504. /**
  40505. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40506. */
  40507. _this._forceIrradianceInFragment = false;
  40508. /**
  40509. * Force normal to face away from face.
  40510. */
  40511. _this._forceNormalForward = false;
  40512. /**
  40513. * Force metallic workflow.
  40514. */
  40515. _this._forceMetallicWorkflow = false;
  40516. /**
  40517. * Stores the available render targets.
  40518. */
  40519. _this._renderTargets = new BABYLON.SmartArray(16);
  40520. /**
  40521. * Sets the global ambient color for the material used in lighting calculations.
  40522. */
  40523. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40524. // Setup the default processing configuration to the scene.
  40525. _this._attachImageProcessingConfiguration(null);
  40526. _this.getRenderTargetTextures = function () {
  40527. _this._renderTargets.reset();
  40528. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40529. _this._renderTargets.push(_this._reflectionTexture);
  40530. }
  40531. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40532. _this._renderTargets.push(_this._refractionTexture);
  40533. }
  40534. return _this._renderTargets;
  40535. };
  40536. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40537. return _this;
  40538. }
  40539. /**
  40540. * Attaches a new image processing configuration to the PBR Material.
  40541. * @param configuration
  40542. */
  40543. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40544. var _this = this;
  40545. if (configuration === this._imageProcessingConfiguration) {
  40546. return;
  40547. }
  40548. // Detaches observer.
  40549. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40550. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40551. }
  40552. // Pick the scene configuration if needed.
  40553. if (!configuration) {
  40554. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40555. }
  40556. else {
  40557. this._imageProcessingConfiguration = configuration;
  40558. }
  40559. // Attaches observer.
  40560. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40561. _this._markAllSubMeshesAsImageProcessingDirty();
  40562. });
  40563. };
  40564. /**
  40565. * Gets the name of the material class.
  40566. */
  40567. PBRBaseMaterial.prototype.getClassName = function () {
  40568. return "PBRBaseMaterial";
  40569. };
  40570. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40571. /**
  40572. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40573. */
  40574. get: function () {
  40575. return this._useLogarithmicDepth;
  40576. },
  40577. /**
  40578. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40579. */
  40580. set: function (value) {
  40581. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40582. },
  40583. enumerable: true,
  40584. configurable: true
  40585. });
  40586. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40587. /**
  40588. * Gets the current transparency mode.
  40589. */
  40590. get: function () {
  40591. return this._transparencyMode;
  40592. },
  40593. /**
  40594. * Sets the transparency mode of the material.
  40595. */
  40596. set: function (value) {
  40597. if (this._transparencyMode === value) {
  40598. return;
  40599. }
  40600. this._transparencyMode = value;
  40601. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40602. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40603. },
  40604. enumerable: true,
  40605. configurable: true
  40606. });
  40607. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40608. /**
  40609. * Returns true if alpha blending should be disabled.
  40610. */
  40611. get: function () {
  40612. return (this._linkRefractionWithTransparency ||
  40613. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40614. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. /**
  40620. * Specifies whether or not this material should be rendered in alpha blend mode.
  40621. */
  40622. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40623. if (this._disableAlphaBlending) {
  40624. return false;
  40625. }
  40626. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40627. };
  40628. /**
  40629. * Specifies if the mesh will require alpha blending.
  40630. * @param mesh - BJS mesh.
  40631. */
  40632. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40633. if (this._disableAlphaBlending) {
  40634. return false;
  40635. }
  40636. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40637. };
  40638. /**
  40639. * Specifies whether or not this material should be rendered in alpha test mode.
  40640. */
  40641. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40642. if (this._forceAlphaTest) {
  40643. return true;
  40644. }
  40645. if (this._linkRefractionWithTransparency) {
  40646. return false;
  40647. }
  40648. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40649. };
  40650. /**
  40651. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40652. */
  40653. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40654. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40655. };
  40656. /**
  40657. * Gets the texture used for the alpha test.
  40658. */
  40659. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40660. return this._albedoTexture;
  40661. };
  40662. /**
  40663. * Specifies that the submesh is ready to be used.
  40664. * @param mesh - BJS mesh.
  40665. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40666. * @param useInstances - Specifies that instances should be used.
  40667. * @returns - boolean indicating that the submesh is ready or not.
  40668. */
  40669. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40670. if (subMesh.effect && this.isFrozen) {
  40671. if (this._wasPreviouslyReady) {
  40672. return true;
  40673. }
  40674. }
  40675. if (!subMesh._materialDefines) {
  40676. subMesh._materialDefines = new PBRMaterialDefines();
  40677. }
  40678. var defines = subMesh._materialDefines;
  40679. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40680. if (defines._renderId === this.getScene().getRenderId()) {
  40681. return true;
  40682. }
  40683. }
  40684. var scene = this.getScene();
  40685. var engine = scene.getEngine();
  40686. if (defines._areTexturesDirty) {
  40687. if (scene.texturesEnabled) {
  40688. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40689. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40690. return false;
  40691. }
  40692. }
  40693. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40694. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40695. return false;
  40696. }
  40697. }
  40698. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40699. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40700. return false;
  40701. }
  40702. }
  40703. var reflectionTexture = this._getReflectionTexture();
  40704. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40705. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40706. return false;
  40707. }
  40708. }
  40709. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40710. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40711. return false;
  40712. }
  40713. }
  40714. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40715. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40716. return false;
  40717. }
  40718. }
  40719. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40720. if (this._metallicTexture) {
  40721. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40722. return false;
  40723. }
  40724. }
  40725. else if (this._reflectivityTexture) {
  40726. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40727. return false;
  40728. }
  40729. }
  40730. if (this._microSurfaceTexture) {
  40731. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40732. return false;
  40733. }
  40734. }
  40735. }
  40736. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40737. // Bump texture cannot be not blocking.
  40738. if (!this._bumpTexture.isReady()) {
  40739. return false;
  40740. }
  40741. }
  40742. var refractionTexture = this._getRefractionTexture();
  40743. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40744. if (!refractionTexture.isReadyOrNotBlocking()) {
  40745. return false;
  40746. }
  40747. }
  40748. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40749. // This is blocking.
  40750. if (!this._environmentBRDFTexture.isReady()) {
  40751. return false;
  40752. }
  40753. }
  40754. }
  40755. }
  40756. if (defines._areImageProcessingDirty) {
  40757. if (!this._imageProcessingConfiguration.isReady()) {
  40758. return false;
  40759. }
  40760. }
  40761. if (!engine.getCaps().standardDerivatives) {
  40762. var bufferMesh = null;
  40763. if (mesh.getClassName() === "InstancedMesh") {
  40764. bufferMesh = mesh.sourceMesh;
  40765. }
  40766. else if (mesh.getClassName() === "Mesh") {
  40767. bufferMesh = mesh;
  40768. }
  40769. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40770. bufferMesh.createNormals(true);
  40771. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40772. }
  40773. }
  40774. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40775. if (effect) {
  40776. scene.resetCachedMaterial();
  40777. subMesh.setEffect(effect, defines);
  40778. this.buildUniformLayout();
  40779. }
  40780. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40781. return false;
  40782. }
  40783. defines._renderId = scene.getRenderId();
  40784. this._wasPreviouslyReady = true;
  40785. return true;
  40786. };
  40787. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40788. if (onCompiled === void 0) { onCompiled = null; }
  40789. if (onError === void 0) { onError = null; }
  40790. if (useInstances === void 0) { useInstances = null; }
  40791. if (useClipPlane === void 0) { useClipPlane = null; }
  40792. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40793. if (!defines.isDirty) {
  40794. return null;
  40795. }
  40796. defines.markAsProcessed();
  40797. var scene = this.getScene();
  40798. var engine = scene.getEngine();
  40799. // Fallbacks
  40800. var fallbacks = new BABYLON.EffectFallbacks();
  40801. var fallbackRank = 0;
  40802. if (defines.USESPHERICALINVERTEX) {
  40803. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40804. }
  40805. if (defines.FOG) {
  40806. fallbacks.addFallback(fallbackRank, "FOG");
  40807. }
  40808. if (defines.POINTSIZE) {
  40809. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40810. }
  40811. if (defines.LOGARITHMICDEPTH) {
  40812. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40813. }
  40814. if (defines.PARALLAX) {
  40815. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40816. }
  40817. if (defines.PARALLAXOCCLUSION) {
  40818. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40819. }
  40820. if (defines.ENVIRONMENTBRDF) {
  40821. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40822. }
  40823. if (defines.TANGENT) {
  40824. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40825. }
  40826. if (defines.BUMP) {
  40827. fallbacks.addFallback(fallbackRank++, "BUMP");
  40828. }
  40829. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40830. if (defines.SPECULARTERM) {
  40831. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40832. }
  40833. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40834. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40835. }
  40836. if (defines.LIGHTMAP) {
  40837. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40838. }
  40839. if (defines.NORMAL) {
  40840. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40841. }
  40842. if (defines.AMBIENT) {
  40843. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40844. }
  40845. if (defines.EMISSIVE) {
  40846. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40847. }
  40848. if (defines.VERTEXCOLOR) {
  40849. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40850. }
  40851. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40852. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40853. }
  40854. if (defines.MORPHTARGETS) {
  40855. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40856. }
  40857. //Attributes
  40858. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40859. if (defines.NORMAL) {
  40860. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40861. }
  40862. if (defines.TANGENT) {
  40863. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40864. }
  40865. if (defines.UV1) {
  40866. attribs.push(BABYLON.VertexBuffer.UVKind);
  40867. }
  40868. if (defines.UV2) {
  40869. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40870. }
  40871. if (defines.VERTEXCOLOR) {
  40872. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40873. }
  40874. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40875. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40876. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40877. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40878. "vFogInfos", "vFogColor", "pointSize",
  40879. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40880. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40881. "mBones",
  40882. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40883. "vLightingIntensity",
  40884. "logarithmicDepthConstant",
  40885. "vSphericalX", "vSphericalY", "vSphericalZ",
  40886. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40887. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40888. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40889. "vTangentSpaceParams"
  40890. ];
  40891. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40892. "bumpSampler", "lightmapSampler", "opacitySampler",
  40893. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40894. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40895. "microSurfaceSampler", "environmentBrdfSampler"];
  40896. var uniformBuffers = ["Material", "Scene"];
  40897. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40898. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40899. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40900. uniformsNames: uniforms,
  40901. uniformBuffersNames: uniformBuffers,
  40902. samplers: samplers,
  40903. defines: defines,
  40904. maxSimultaneousLights: this._maxSimultaneousLights
  40905. });
  40906. var join = defines.toString();
  40907. return engine.createEffect("pbr", {
  40908. attributes: attribs,
  40909. uniformsNames: uniforms,
  40910. uniformBuffersNames: uniformBuffers,
  40911. samplers: samplers,
  40912. defines: join,
  40913. fallbacks: fallbacks,
  40914. onCompiled: onCompiled,
  40915. onError: onError,
  40916. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40917. }, engine);
  40918. };
  40919. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40920. if (useInstances === void 0) { useInstances = null; }
  40921. if (useClipPlane === void 0) { useClipPlane = null; }
  40922. var scene = this.getScene();
  40923. var engine = scene.getEngine();
  40924. // Lights
  40925. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40926. defines._needNormals = true;
  40927. // Textures
  40928. if (defines._areTexturesDirty) {
  40929. defines._needUVs = false;
  40930. if (scene.texturesEnabled) {
  40931. if (scene.getEngine().getCaps().textureLOD) {
  40932. defines.LODBASEDMICROSFURACE = true;
  40933. }
  40934. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40935. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40936. }
  40937. else {
  40938. defines.ALBEDO = false;
  40939. }
  40940. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40941. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40942. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40943. }
  40944. else {
  40945. defines.AMBIENT = false;
  40946. }
  40947. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40949. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40950. }
  40951. else {
  40952. defines.OPACITY = false;
  40953. }
  40954. var reflectionTexture = this._getReflectionTexture();
  40955. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40956. defines.REFLECTION = true;
  40957. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40958. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40959. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40960. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40961. defines.INVERTCUBICMAP = true;
  40962. }
  40963. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40964. switch (reflectionTexture.coordinatesMode) {
  40965. case BABYLON.Texture.CUBIC_MODE:
  40966. case BABYLON.Texture.INVCUBIC_MODE:
  40967. defines.REFLECTIONMAP_CUBIC = true;
  40968. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40969. break;
  40970. case BABYLON.Texture.EXPLICIT_MODE:
  40971. defines.REFLECTIONMAP_EXPLICIT = true;
  40972. break;
  40973. case BABYLON.Texture.PLANAR_MODE:
  40974. defines.REFLECTIONMAP_PLANAR = true;
  40975. break;
  40976. case BABYLON.Texture.PROJECTION_MODE:
  40977. defines.REFLECTIONMAP_PROJECTION = true;
  40978. break;
  40979. case BABYLON.Texture.SKYBOX_MODE:
  40980. defines.REFLECTIONMAP_SKYBOX = true;
  40981. break;
  40982. case BABYLON.Texture.SPHERICAL_MODE:
  40983. defines.REFLECTIONMAP_SPHERICAL = true;
  40984. break;
  40985. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40986. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40987. break;
  40988. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40989. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40990. break;
  40991. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40992. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40993. break;
  40994. }
  40995. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40996. if (reflectionTexture.sphericalPolynomial) {
  40997. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40998. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40999. defines.USESPHERICALINVERTEX = false;
  41000. }
  41001. else {
  41002. defines.USESPHERICALINVERTEX = true;
  41003. }
  41004. }
  41005. }
  41006. }
  41007. else {
  41008. defines.REFLECTION = false;
  41009. defines.REFLECTIONMAP_3D = false;
  41010. defines.REFLECTIONMAP_SPHERICAL = false;
  41011. defines.REFLECTIONMAP_PLANAR = false;
  41012. defines.REFLECTIONMAP_CUBIC = false;
  41013. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41014. defines.REFLECTIONMAP_PROJECTION = false;
  41015. defines.REFLECTIONMAP_SKYBOX = false;
  41016. defines.REFLECTIONMAP_EXPLICIT = false;
  41017. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41018. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41019. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41020. defines.INVERTCUBICMAP = false;
  41021. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41022. defines.USESPHERICALINVERTEX = false;
  41023. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41024. defines.LODINREFLECTIONALPHA = false;
  41025. defines.GAMMAREFLECTION = false;
  41026. }
  41027. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41028. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41029. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41030. }
  41031. else {
  41032. defines.LIGHTMAP = false;
  41033. }
  41034. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41035. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41036. }
  41037. else {
  41038. defines.EMISSIVE = false;
  41039. }
  41040. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41041. if (this._metallicTexture) {
  41042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41043. defines.METALLICWORKFLOW = true;
  41044. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41045. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41046. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41047. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41048. }
  41049. else if (this._reflectivityTexture) {
  41050. defines.METALLICWORKFLOW = false;
  41051. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41052. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41053. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41054. }
  41055. else {
  41056. defines.METALLICWORKFLOW = false;
  41057. defines.REFLECTIVITY = false;
  41058. }
  41059. if (this._microSurfaceTexture) {
  41060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41061. }
  41062. else {
  41063. defines.MICROSURFACEMAP = false;
  41064. }
  41065. }
  41066. else {
  41067. defines.REFLECTIVITY = false;
  41068. defines.MICROSURFACEMAP = false;
  41069. }
  41070. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41072. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41073. defines.PARALLAX = true;
  41074. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41075. }
  41076. else {
  41077. defines.PARALLAX = false;
  41078. }
  41079. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41080. }
  41081. else {
  41082. defines.BUMP = false;
  41083. }
  41084. var refractionTexture = this._getRefractionTexture();
  41085. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41086. defines.REFRACTION = true;
  41087. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41088. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41089. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41090. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41091. if (this._linkRefractionWithTransparency) {
  41092. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41093. }
  41094. }
  41095. else {
  41096. defines.REFRACTION = false;
  41097. }
  41098. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41099. defines.ENVIRONMENTBRDF = true;
  41100. }
  41101. else {
  41102. defines.ENVIRONMENTBRDF = false;
  41103. }
  41104. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41105. defines.ALPHAFROMALBEDO = true;
  41106. }
  41107. else {
  41108. defines.ALPHAFROMALBEDO = false;
  41109. }
  41110. }
  41111. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41112. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41113. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41114. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41115. defines.METALLICWORKFLOW = true;
  41116. }
  41117. else {
  41118. defines.METALLICWORKFLOW = false;
  41119. }
  41120. if (!this.backFaceCulling && this._twoSidedLighting) {
  41121. defines.TWOSIDEDLIGHTING = true;
  41122. }
  41123. else {
  41124. defines.TWOSIDEDLIGHTING = false;
  41125. }
  41126. defines.ALPHATESTVALUE = this._alphaCutOff;
  41127. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41128. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41129. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41130. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41131. }
  41132. if (defines._areImageProcessingDirty) {
  41133. this._imageProcessingConfiguration.prepareDefines(defines);
  41134. }
  41135. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41136. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41137. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41138. // Misc.
  41139. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41140. // Values that need to be evaluated on every frame
  41141. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41142. // Attribs
  41143. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41144. };
  41145. /**
  41146. * Force shader compilation
  41147. */
  41148. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41149. var _this = this;
  41150. var localOptions = __assign({ clipPlane: false }, options);
  41151. var defines = new PBRMaterialDefines();
  41152. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41153. if (effect.isReady()) {
  41154. if (onCompiled) {
  41155. onCompiled(this);
  41156. }
  41157. }
  41158. else {
  41159. effect.onCompileObservable.add(function () {
  41160. if (onCompiled) {
  41161. onCompiled(_this);
  41162. }
  41163. });
  41164. }
  41165. };
  41166. /**
  41167. * Initializes the uniform buffer layout for the shader.
  41168. */
  41169. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41170. // Order is important !
  41171. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41172. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41173. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41174. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41175. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41176. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41177. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41178. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41179. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41180. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41181. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41182. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41183. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41184. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41185. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41186. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41187. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41188. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41189. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41190. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41191. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41192. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41193. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41194. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41195. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41196. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41197. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41198. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41199. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41200. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41201. this._uniformBuffer.addUniform("pointSize", 1);
  41202. this._uniformBuffer.create();
  41203. };
  41204. /**
  41205. * Unbinds the textures.
  41206. */
  41207. PBRBaseMaterial.prototype.unbind = function () {
  41208. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41209. this._uniformBuffer.setTexture("reflectionSampler", null);
  41210. }
  41211. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41212. this._uniformBuffer.setTexture("refractionSampler", null);
  41213. }
  41214. _super.prototype.unbind.call(this);
  41215. };
  41216. /**
  41217. * Binds the submesh data.
  41218. * @param world - The world matrix.
  41219. * @param mesh - The BJS mesh.
  41220. * @param subMesh - A submesh of the BJS mesh.
  41221. */
  41222. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41223. var scene = this.getScene();
  41224. var defines = subMesh._materialDefines;
  41225. if (!defines) {
  41226. return;
  41227. }
  41228. var effect = subMesh.effect;
  41229. if (!effect) {
  41230. return;
  41231. }
  41232. this._activeEffect = effect;
  41233. // Matrices
  41234. this.bindOnlyWorldMatrix(world);
  41235. // Normal Matrix
  41236. if (defines.OBJECTSPACE_NORMALMAP) {
  41237. world.toNormalMatrix(this._normalMatrix);
  41238. this.bindOnlyNormalMatrix(this._normalMatrix);
  41239. }
  41240. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41241. // Bones
  41242. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41243. var reflectionTexture = null;
  41244. if (mustRebind) {
  41245. this._uniformBuffer.bindToEffect(effect, "Material");
  41246. this.bindViewProjection(effect);
  41247. reflectionTexture = this._getReflectionTexture();
  41248. var refractionTexture = this._getRefractionTexture();
  41249. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41250. // Texture uniforms
  41251. if (scene.texturesEnabled) {
  41252. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41253. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41254. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41255. }
  41256. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41257. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41258. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41259. }
  41260. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41261. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41262. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41263. }
  41264. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41265. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41266. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41267. if (reflectionTexture.boundingBoxSize) {
  41268. var cubeTexture = reflectionTexture;
  41269. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41270. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41271. }
  41272. var polynomials = reflectionTexture.sphericalPolynomial;
  41273. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41274. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41275. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41276. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41277. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41278. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41279. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41280. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41281. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41282. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41283. }
  41284. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41285. }
  41286. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41287. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41288. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41289. }
  41290. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41291. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41292. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41293. }
  41294. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41295. if (this._metallicTexture) {
  41296. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41297. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41298. }
  41299. else if (this._reflectivityTexture) {
  41300. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41301. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41302. }
  41303. if (this._microSurfaceTexture) {
  41304. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41305. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41306. }
  41307. }
  41308. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41309. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41310. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41311. if (scene._mirroredCameraPosition) {
  41312. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41313. }
  41314. else {
  41315. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41316. }
  41317. }
  41318. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41319. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41320. var depth = 1.0;
  41321. if (!refractionTexture.isCube) {
  41322. if (refractionTexture.depth) {
  41323. depth = refractionTexture.depth;
  41324. }
  41325. }
  41326. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41327. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41328. }
  41329. }
  41330. // Point size
  41331. if (this.pointsCloud) {
  41332. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41333. }
  41334. // Colors
  41335. if (defines.METALLICWORKFLOW) {
  41336. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41337. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41338. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41339. }
  41340. else {
  41341. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41342. }
  41343. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41344. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41345. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41346. // Misc
  41347. this._lightingInfos.x = this._directIntensity;
  41348. this._lightingInfos.y = this._emissiveIntensity;
  41349. this._lightingInfos.z = this._environmentIntensity;
  41350. this._lightingInfos.w = this._specularIntensity;
  41351. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41352. }
  41353. // Textures
  41354. if (scene.texturesEnabled) {
  41355. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41356. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41357. }
  41358. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41359. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41360. }
  41361. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41362. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41363. }
  41364. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41365. if (defines.LODBASEDMICROSFURACE) {
  41366. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41367. }
  41368. else {
  41369. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41370. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41371. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41372. }
  41373. }
  41374. if (defines.ENVIRONMENTBRDF) {
  41375. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41376. }
  41377. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41378. if (defines.LODBASEDMICROSFURACE) {
  41379. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41380. }
  41381. else {
  41382. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41383. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41384. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41385. }
  41386. }
  41387. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41388. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41389. }
  41390. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41391. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41392. }
  41393. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41394. if (this._metallicTexture) {
  41395. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41396. }
  41397. else if (this._reflectivityTexture) {
  41398. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41399. }
  41400. if (this._microSurfaceTexture) {
  41401. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41402. }
  41403. }
  41404. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41405. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41406. }
  41407. }
  41408. // Clip plane
  41409. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41410. // Colors
  41411. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41412. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41413. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41414. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41415. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41416. }
  41417. if (mustRebind || !this.isFrozen) {
  41418. // Lights
  41419. if (scene.lightsEnabled && !this._disableLighting) {
  41420. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41421. }
  41422. // View
  41423. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41424. this.bindView(effect);
  41425. }
  41426. // Fog
  41427. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41428. // Morph targets
  41429. if (defines.NUM_MORPH_INFLUENCERS) {
  41430. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41431. }
  41432. // image processing
  41433. this._imageProcessingConfiguration.bind(this._activeEffect);
  41434. // Log. depth
  41435. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41436. }
  41437. this._uniformBuffer.update();
  41438. this._afterBind(mesh);
  41439. };
  41440. /**
  41441. * Returns the animatable textures.
  41442. * @returns - Array of animatable textures.
  41443. */
  41444. PBRBaseMaterial.prototype.getAnimatables = function () {
  41445. var results = [];
  41446. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41447. results.push(this._albedoTexture);
  41448. }
  41449. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41450. results.push(this._ambientTexture);
  41451. }
  41452. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41453. results.push(this._opacityTexture);
  41454. }
  41455. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41456. results.push(this._reflectionTexture);
  41457. }
  41458. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41459. results.push(this._emissiveTexture);
  41460. }
  41461. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41462. results.push(this._metallicTexture);
  41463. }
  41464. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41465. results.push(this._reflectivityTexture);
  41466. }
  41467. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41468. results.push(this._bumpTexture);
  41469. }
  41470. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41471. results.push(this._lightmapTexture);
  41472. }
  41473. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41474. results.push(this._refractionTexture);
  41475. }
  41476. return results;
  41477. };
  41478. /**
  41479. * Returns the texture used for reflections.
  41480. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41481. */
  41482. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41483. if (this._reflectionTexture) {
  41484. return this._reflectionTexture;
  41485. }
  41486. return this.getScene().environmentTexture;
  41487. };
  41488. /**
  41489. * Returns the texture used for refraction or null if none is used.
  41490. * @returns - Refection texture if present. If no refraction texture and refraction
  41491. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41492. */
  41493. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41494. if (this._refractionTexture) {
  41495. return this._refractionTexture;
  41496. }
  41497. if (this._linkRefractionWithTransparency) {
  41498. return this.getScene().environmentTexture;
  41499. }
  41500. return null;
  41501. };
  41502. /**
  41503. * Disposes the resources of the material.
  41504. * @param forceDisposeEffect - Forces the disposal of effects.
  41505. * @param forceDisposeTextures - Forces the disposal of all textures.
  41506. */
  41507. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41508. if (forceDisposeTextures) {
  41509. if (this._albedoTexture) {
  41510. this._albedoTexture.dispose();
  41511. }
  41512. if (this._ambientTexture) {
  41513. this._ambientTexture.dispose();
  41514. }
  41515. if (this._opacityTexture) {
  41516. this._opacityTexture.dispose();
  41517. }
  41518. if (this._reflectionTexture) {
  41519. this._reflectionTexture.dispose();
  41520. }
  41521. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41522. this._environmentBRDFTexture.dispose();
  41523. }
  41524. if (this._emissiveTexture) {
  41525. this._emissiveTexture.dispose();
  41526. }
  41527. if (this._metallicTexture) {
  41528. this._metallicTexture.dispose();
  41529. }
  41530. if (this._reflectivityTexture) {
  41531. this._reflectivityTexture.dispose();
  41532. }
  41533. if (this._bumpTexture) {
  41534. this._bumpTexture.dispose();
  41535. }
  41536. if (this._lightmapTexture) {
  41537. this._lightmapTexture.dispose();
  41538. }
  41539. if (this._refractionTexture) {
  41540. this._refractionTexture.dispose();
  41541. }
  41542. }
  41543. this._renderTargets.dispose();
  41544. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41545. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41546. }
  41547. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41548. };
  41549. /**
  41550. * Stores the reflectivity values based on metallic roughness workflow.
  41551. */
  41552. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41553. __decorate([
  41554. BABYLON.serializeAsImageProcessingConfiguration()
  41555. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41556. __decorate([
  41557. BABYLON.serialize()
  41558. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41559. __decorate([
  41560. BABYLON.serialize()
  41561. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41562. return PBRBaseMaterial;
  41563. }(BABYLON.PushMaterial));
  41564. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41565. })(BABYLON || (BABYLON = {}));
  41566. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41567. var BABYLON;
  41568. (function (BABYLON) {
  41569. /**
  41570. * The Physically based simple base material of BJS.
  41571. *
  41572. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41573. * It is used as the base class for both the specGloss and metalRough conventions.
  41574. */
  41575. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41576. __extends(PBRBaseSimpleMaterial, _super);
  41577. /**
  41578. * Instantiates a new PBRMaterial instance.
  41579. *
  41580. * @param name The material name
  41581. * @param scene The scene the material will be use in.
  41582. */
  41583. function PBRBaseSimpleMaterial(name, scene) {
  41584. var _this = _super.call(this, name, scene) || this;
  41585. /**
  41586. * Number of Simultaneous lights allowed on the material.
  41587. */
  41588. _this.maxSimultaneousLights = 4;
  41589. /**
  41590. * If sets to true, disables all the lights affecting the material.
  41591. */
  41592. _this.disableLighting = false;
  41593. /**
  41594. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41595. */
  41596. _this.invertNormalMapX = false;
  41597. /**
  41598. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41599. */
  41600. _this.invertNormalMapY = false;
  41601. /**
  41602. * Emissivie color used to self-illuminate the model.
  41603. */
  41604. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41605. /**
  41606. * Occlusion Channel Strenght.
  41607. */
  41608. _this.occlusionStrength = 1.0;
  41609. _this.useLightmapAsShadowmap = false;
  41610. _this._useAlphaFromAlbedoTexture = true;
  41611. _this._useAmbientInGrayScale = true;
  41612. return _this;
  41613. }
  41614. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41615. /**
  41616. * Gets the current double sided mode.
  41617. */
  41618. get: function () {
  41619. return this._twoSidedLighting;
  41620. },
  41621. /**
  41622. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41623. */
  41624. set: function (value) {
  41625. if (this._twoSidedLighting === value) {
  41626. return;
  41627. }
  41628. this._twoSidedLighting = value;
  41629. this.backFaceCulling = !value;
  41630. this._markAllSubMeshesAsTexturesDirty();
  41631. },
  41632. enumerable: true,
  41633. configurable: true
  41634. });
  41635. /**
  41636. * Return the active textures of the material.
  41637. */
  41638. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41639. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41640. if (this.environmentTexture) {
  41641. activeTextures.push(this.environmentTexture);
  41642. }
  41643. if (this.normalTexture) {
  41644. activeTextures.push(this.normalTexture);
  41645. }
  41646. if (this.emissiveTexture) {
  41647. activeTextures.push(this.emissiveTexture);
  41648. }
  41649. if (this.occlusionTexture) {
  41650. activeTextures.push(this.occlusionTexture);
  41651. }
  41652. if (this.lightmapTexture) {
  41653. activeTextures.push(this.lightmapTexture);
  41654. }
  41655. return activeTextures;
  41656. };
  41657. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41658. if (_super.prototype.hasTexture.call(this, texture)) {
  41659. return true;
  41660. }
  41661. if (this.lightmapTexture === texture) {
  41662. return true;
  41663. }
  41664. return false;
  41665. };
  41666. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41667. return "PBRBaseSimpleMaterial";
  41668. };
  41669. __decorate([
  41670. BABYLON.serialize(),
  41671. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41672. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41673. __decorate([
  41674. BABYLON.serialize(),
  41675. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41676. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41677. __decorate([
  41678. BABYLON.serializeAsTexture(),
  41679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41680. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41681. __decorate([
  41682. BABYLON.serialize(),
  41683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41684. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41685. __decorate([
  41686. BABYLON.serialize(),
  41687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41688. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41689. __decorate([
  41690. BABYLON.serializeAsTexture(),
  41691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41692. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41693. __decorate([
  41694. BABYLON.serializeAsColor3("emissive"),
  41695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41696. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41697. __decorate([
  41698. BABYLON.serializeAsTexture(),
  41699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41700. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41701. __decorate([
  41702. BABYLON.serialize(),
  41703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41704. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41705. __decorate([
  41706. BABYLON.serializeAsTexture(),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41708. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41712. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41713. __decorate([
  41714. BABYLON.serialize()
  41715. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41716. __decorate([
  41717. BABYLON.serializeAsTexture(),
  41718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41719. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41720. __decorate([
  41721. BABYLON.serialize(),
  41722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41723. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41724. return PBRBaseSimpleMaterial;
  41725. }(BABYLON.PBRBaseMaterial));
  41726. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41727. })(BABYLON || (BABYLON = {}));
  41728. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41729. var BABYLON;
  41730. (function (BABYLON) {
  41731. /**
  41732. * The Physically based material of BJS.
  41733. *
  41734. * This offers the main features of a standard PBR material.
  41735. * For more information, please refer to the documentation :
  41736. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41737. */
  41738. var PBRMaterial = /** @class */ (function (_super) {
  41739. __extends(PBRMaterial, _super);
  41740. /**
  41741. * Instantiates a new PBRMaterial instance.
  41742. *
  41743. * @param name The material name
  41744. * @param scene The scene the material will be use in.
  41745. */
  41746. function PBRMaterial(name, scene) {
  41747. var _this = _super.call(this, name, scene) || this;
  41748. /**
  41749. * Intensity of the direct lights e.g. the four lights available in your scene.
  41750. * This impacts both the direct diffuse and specular highlights.
  41751. */
  41752. _this.directIntensity = 1.0;
  41753. /**
  41754. * Intensity of the emissive part of the material.
  41755. * This helps controlling the emissive effect without modifying the emissive color.
  41756. */
  41757. _this.emissiveIntensity = 1.0;
  41758. /**
  41759. * Intensity of the environment e.g. how much the environment will light the object
  41760. * either through harmonics for rough material or through the refelction for shiny ones.
  41761. */
  41762. _this.environmentIntensity = 1.0;
  41763. /**
  41764. * This is a special control allowing the reduction of the specular highlights coming from the
  41765. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41766. */
  41767. _this.specularIntensity = 1.0;
  41768. /**
  41769. * Debug Control allowing disabling the bump map on this material.
  41770. */
  41771. _this.disableBumpMap = false;
  41772. /**
  41773. * AKA Occlusion Texture Intensity in other nomenclature.
  41774. */
  41775. _this.ambientTextureStrength = 1.0;
  41776. /**
  41777. * The color of a material in ambient lighting.
  41778. */
  41779. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41780. /**
  41781. * AKA Diffuse Color in other nomenclature.
  41782. */
  41783. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41784. /**
  41785. * AKA Specular Color in other nomenclature.
  41786. */
  41787. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41788. /**
  41789. * The color reflected from the material.
  41790. */
  41791. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41792. /**
  41793. * The color emitted from the material.
  41794. */
  41795. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41796. /**
  41797. * AKA Glossiness in other nomenclature.
  41798. */
  41799. _this.microSurface = 1.0;
  41800. /**
  41801. * source material index of refraction (IOR)' / 'destination material IOR.
  41802. */
  41803. _this.indexOfRefraction = 0.66;
  41804. /**
  41805. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41806. */
  41807. _this.invertRefractionY = false;
  41808. /**
  41809. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41810. * Materials half opaque for instance using refraction could benefit from this control.
  41811. */
  41812. _this.linkRefractionWithTransparency = false;
  41813. _this.useLightmapAsShadowmap = false;
  41814. /**
  41815. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41816. */
  41817. _this.useAlphaFromAlbedoTexture = false;
  41818. /**
  41819. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41820. */
  41821. _this.forceAlphaTest = false;
  41822. /**
  41823. * Defines the alpha limits in alpha test mode.
  41824. */
  41825. _this.alphaCutOff = 0.4;
  41826. /**
  41827. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41828. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41829. */
  41830. _this.useSpecularOverAlpha = true;
  41831. /**
  41832. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41833. */
  41834. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41835. /**
  41836. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41837. */
  41838. _this.useRoughnessFromMetallicTextureAlpha = true;
  41839. /**
  41840. * Specifies if the metallic texture contains the roughness information in its green channel.
  41841. */
  41842. _this.useRoughnessFromMetallicTextureGreen = false;
  41843. /**
  41844. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41845. */
  41846. _this.useMetallnessFromMetallicTextureBlue = false;
  41847. /**
  41848. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41849. */
  41850. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41851. /**
  41852. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41853. */
  41854. _this.useAmbientInGrayScale = false;
  41855. /**
  41856. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41857. * The material will try to infer what glossiness each pixel should be.
  41858. */
  41859. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41860. /**
  41861. * BJS is using an harcoded light falloff based on a manually sets up range.
  41862. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41863. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41864. */
  41865. _this.usePhysicalLightFalloff = true;
  41866. /**
  41867. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41868. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41869. */
  41870. _this.useRadianceOverAlpha = true;
  41871. /**
  41872. * Allows using an object space normal map (instead of tangent space).
  41873. */
  41874. _this.useObjectSpaceNormalMap = false;
  41875. /**
  41876. * Allows using the bump map in parallax mode.
  41877. */
  41878. _this.useParallax = false;
  41879. /**
  41880. * Allows using the bump map in parallax occlusion mode.
  41881. */
  41882. _this.useParallaxOcclusion = false;
  41883. /**
  41884. * Controls the scale bias of the parallax mode.
  41885. */
  41886. _this.parallaxScaleBias = 0.05;
  41887. /**
  41888. * If sets to true, disables all the lights affecting the material.
  41889. */
  41890. _this.disableLighting = false;
  41891. /**
  41892. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41893. */
  41894. _this.forceIrradianceInFragment = false;
  41895. /**
  41896. * Number of Simultaneous lights allowed on the material.
  41897. */
  41898. _this.maxSimultaneousLights = 4;
  41899. /**
  41900. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41901. */
  41902. _this.invertNormalMapX = false;
  41903. /**
  41904. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41905. */
  41906. _this.invertNormalMapY = false;
  41907. /**
  41908. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41909. */
  41910. _this.twoSidedLighting = false;
  41911. /**
  41912. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41913. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41914. */
  41915. _this.useAlphaFresnel = false;
  41916. /**
  41917. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41918. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41919. */
  41920. _this.useLinearAlphaFresnel = false;
  41921. /**
  41922. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41923. * And/Or occlude the blended part.
  41924. */
  41925. _this.environmentBRDFTexture = null;
  41926. /**
  41927. * Force normal to face away from face.
  41928. */
  41929. _this.forceNormalForward = false;
  41930. /**
  41931. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41932. * makes the reflect vector face the model (under horizon).
  41933. */
  41934. _this.useHorizonOcclusion = true;
  41935. /**
  41936. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41937. * too much the area relying on ambient texture to define their ambient occlusion.
  41938. */
  41939. _this.useRadianceOcclusion = true;
  41940. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41941. return _this;
  41942. }
  41943. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41944. /**
  41945. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41946. */
  41947. get: function () {
  41948. return this._PBRMATERIAL_OPAQUE;
  41949. },
  41950. enumerable: true,
  41951. configurable: true
  41952. });
  41953. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41954. /**
  41955. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41956. */
  41957. get: function () {
  41958. return this._PBRMATERIAL_ALPHATEST;
  41959. },
  41960. enumerable: true,
  41961. configurable: true
  41962. });
  41963. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41964. /**
  41965. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41966. */
  41967. get: function () {
  41968. return this._PBRMATERIAL_ALPHABLEND;
  41969. },
  41970. enumerable: true,
  41971. configurable: true
  41972. });
  41973. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41974. /**
  41975. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41976. * They are also discarded below the alpha cutoff threshold to improve performances.
  41977. */
  41978. get: function () {
  41979. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41980. },
  41981. enumerable: true,
  41982. configurable: true
  41983. });
  41984. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41985. /**
  41986. * Gets the image processing configuration used either in this material.
  41987. */
  41988. get: function () {
  41989. return this._imageProcessingConfiguration;
  41990. },
  41991. /**
  41992. * Sets the Default image processing configuration used either in the this material.
  41993. *
  41994. * If sets to null, the scene one is in use.
  41995. */
  41996. set: function (value) {
  41997. this._attachImageProcessingConfiguration(value);
  41998. // Ensure the effect will be rebuilt.
  41999. this._markAllSubMeshesAsTexturesDirty();
  42000. },
  42001. enumerable: true,
  42002. configurable: true
  42003. });
  42004. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42005. /**
  42006. * Gets wether the color curves effect is enabled.
  42007. */
  42008. get: function () {
  42009. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42010. },
  42011. /**
  42012. * Sets wether the color curves effect is enabled.
  42013. */
  42014. set: function (value) {
  42015. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42016. },
  42017. enumerable: true,
  42018. configurable: true
  42019. });
  42020. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42021. /**
  42022. * Gets wether the color grading effect is enabled.
  42023. */
  42024. get: function () {
  42025. return this.imageProcessingConfiguration.colorGradingEnabled;
  42026. },
  42027. /**
  42028. * Gets wether the color grading effect is enabled.
  42029. */
  42030. set: function (value) {
  42031. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42037. /**
  42038. * Gets wether tonemapping is enabled or not.
  42039. */
  42040. get: function () {
  42041. return this._imageProcessingConfiguration.toneMappingEnabled;
  42042. },
  42043. /**
  42044. * Sets wether tonemapping is enabled or not
  42045. */
  42046. set: function (value) {
  42047. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42048. },
  42049. enumerable: true,
  42050. configurable: true
  42051. });
  42052. ;
  42053. ;
  42054. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42055. /**
  42056. * The camera exposure used on this material.
  42057. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42058. * This corresponds to a photographic exposure.
  42059. */
  42060. get: function () {
  42061. return this._imageProcessingConfiguration.exposure;
  42062. },
  42063. /**
  42064. * The camera exposure used on this material.
  42065. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42066. * This corresponds to a photographic exposure.
  42067. */
  42068. set: function (value) {
  42069. this._imageProcessingConfiguration.exposure = value;
  42070. },
  42071. enumerable: true,
  42072. configurable: true
  42073. });
  42074. ;
  42075. ;
  42076. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42077. /**
  42078. * Gets The camera contrast used on this material.
  42079. */
  42080. get: function () {
  42081. return this._imageProcessingConfiguration.contrast;
  42082. },
  42083. /**
  42084. * Sets The camera contrast used on this material.
  42085. */
  42086. set: function (value) {
  42087. this._imageProcessingConfiguration.contrast = value;
  42088. },
  42089. enumerable: true,
  42090. configurable: true
  42091. });
  42092. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42093. /**
  42094. * Gets the Color Grading 2D Lookup Texture.
  42095. */
  42096. get: function () {
  42097. return this._imageProcessingConfiguration.colorGradingTexture;
  42098. },
  42099. /**
  42100. * Sets the Color Grading 2D Lookup Texture.
  42101. */
  42102. set: function (value) {
  42103. this._imageProcessingConfiguration.colorGradingTexture = value;
  42104. },
  42105. enumerable: true,
  42106. configurable: true
  42107. });
  42108. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42109. /**
  42110. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42111. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42112. * 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;
  42113. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42114. */
  42115. get: function () {
  42116. return this._imageProcessingConfiguration.colorCurves;
  42117. },
  42118. /**
  42119. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42120. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42121. * 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;
  42122. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42123. */
  42124. set: function (value) {
  42125. this._imageProcessingConfiguration.colorCurves = value;
  42126. },
  42127. enumerable: true,
  42128. configurable: true
  42129. });
  42130. /**
  42131. * Returns the name of this material class.
  42132. */
  42133. PBRMaterial.prototype.getClassName = function () {
  42134. return "PBRMaterial";
  42135. };
  42136. /**
  42137. * Returns an array of the actively used textures.
  42138. * @returns - Array of BaseTextures
  42139. */
  42140. PBRMaterial.prototype.getActiveTextures = function () {
  42141. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42142. if (this._albedoTexture) {
  42143. activeTextures.push(this._albedoTexture);
  42144. }
  42145. if (this._ambientTexture) {
  42146. activeTextures.push(this._ambientTexture);
  42147. }
  42148. if (this._opacityTexture) {
  42149. activeTextures.push(this._opacityTexture);
  42150. }
  42151. if (this._reflectionTexture) {
  42152. activeTextures.push(this._reflectionTexture);
  42153. }
  42154. if (this._emissiveTexture) {
  42155. activeTextures.push(this._emissiveTexture);
  42156. }
  42157. if (this._reflectivityTexture) {
  42158. activeTextures.push(this._reflectivityTexture);
  42159. }
  42160. if (this._metallicTexture) {
  42161. activeTextures.push(this._metallicTexture);
  42162. }
  42163. if (this._microSurfaceTexture) {
  42164. activeTextures.push(this._microSurfaceTexture);
  42165. }
  42166. if (this._bumpTexture) {
  42167. activeTextures.push(this._bumpTexture);
  42168. }
  42169. if (this._lightmapTexture) {
  42170. activeTextures.push(this._lightmapTexture);
  42171. }
  42172. if (this._refractionTexture) {
  42173. activeTextures.push(this._refractionTexture);
  42174. }
  42175. return activeTextures;
  42176. };
  42177. /**
  42178. * Checks to see if a texture is used in the material.
  42179. * @param texture - Base texture to use.
  42180. * @returns - Boolean specifying if a texture is used in the material.
  42181. */
  42182. PBRMaterial.prototype.hasTexture = function (texture) {
  42183. if (_super.prototype.hasTexture.call(this, texture)) {
  42184. return true;
  42185. }
  42186. if (this._albedoTexture === texture) {
  42187. return true;
  42188. }
  42189. if (this._ambientTexture === texture) {
  42190. return true;
  42191. }
  42192. if (this._opacityTexture === texture) {
  42193. return true;
  42194. }
  42195. if (this._reflectionTexture === texture) {
  42196. return true;
  42197. }
  42198. if (this._reflectivityTexture === texture) {
  42199. return true;
  42200. }
  42201. if (this._metallicTexture === texture) {
  42202. return true;
  42203. }
  42204. if (this._microSurfaceTexture === texture) {
  42205. return true;
  42206. }
  42207. if (this._bumpTexture === texture) {
  42208. return true;
  42209. }
  42210. if (this._lightmapTexture === texture) {
  42211. return true;
  42212. }
  42213. if (this._refractionTexture === texture) {
  42214. return true;
  42215. }
  42216. return false;
  42217. };
  42218. /**
  42219. * Makes a duplicate of the current material.
  42220. * @param name - name to use for the new material.
  42221. */
  42222. PBRMaterial.prototype.clone = function (name) {
  42223. var _this = this;
  42224. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42225. clone.id = name;
  42226. clone.name = name;
  42227. return clone;
  42228. };
  42229. /**
  42230. * Serializes this PBR Material.
  42231. * @returns - An object with the serialized material.
  42232. */
  42233. PBRMaterial.prototype.serialize = function () {
  42234. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42235. serializationObject.customType = "BABYLON.PBRMaterial";
  42236. return serializationObject;
  42237. };
  42238. // Statics
  42239. /**
  42240. * Parses a PBR Material from a serialized object.
  42241. * @param source - Serialized object.
  42242. * @param scene - BJS scene instance.
  42243. * @param rootUrl - url for the scene object
  42244. * @returns - PBRMaterial
  42245. */
  42246. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42247. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42248. };
  42249. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42250. /**
  42251. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42252. */
  42253. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42254. /**
  42255. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42256. */
  42257. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42258. /**
  42259. * 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.
  42260. * They are also discarded below the alpha cutoff threshold to improve performances.
  42261. */
  42262. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42263. __decorate([
  42264. BABYLON.serialize(),
  42265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42266. ], PBRMaterial.prototype, "directIntensity", void 0);
  42267. __decorate([
  42268. BABYLON.serialize(),
  42269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42270. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42271. __decorate([
  42272. BABYLON.serialize(),
  42273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42274. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42275. __decorate([
  42276. BABYLON.serialize(),
  42277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42278. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42279. __decorate([
  42280. BABYLON.serialize(),
  42281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42282. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42283. __decorate([
  42284. BABYLON.serializeAsTexture(),
  42285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42286. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42287. __decorate([
  42288. BABYLON.serializeAsTexture(),
  42289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42290. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42291. __decorate([
  42292. BABYLON.serialize(),
  42293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42294. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42295. __decorate([
  42296. BABYLON.serializeAsTexture(),
  42297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42298. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42299. __decorate([
  42300. BABYLON.serializeAsTexture(),
  42301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42302. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42303. __decorate([
  42304. BABYLON.serializeAsTexture(),
  42305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42306. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42307. __decorate([
  42308. BABYLON.serializeAsTexture(),
  42309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42310. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42311. __decorate([
  42312. BABYLON.serializeAsTexture(),
  42313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42314. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42315. __decorate([
  42316. BABYLON.serialize(),
  42317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42318. ], PBRMaterial.prototype, "metallic", void 0);
  42319. __decorate([
  42320. BABYLON.serialize(),
  42321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42322. ], PBRMaterial.prototype, "roughness", void 0);
  42323. __decorate([
  42324. BABYLON.serializeAsTexture(),
  42325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42326. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42327. __decorate([
  42328. BABYLON.serializeAsTexture(),
  42329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42330. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42331. __decorate([
  42332. BABYLON.serializeAsTexture(),
  42333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42334. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42335. __decorate([
  42336. BABYLON.serializeAsTexture(),
  42337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42338. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42339. __decorate([
  42340. BABYLON.serializeAsColor3("ambient"),
  42341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42342. ], PBRMaterial.prototype, "ambientColor", void 0);
  42343. __decorate([
  42344. BABYLON.serializeAsColor3("albedo"),
  42345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42346. ], PBRMaterial.prototype, "albedoColor", void 0);
  42347. __decorate([
  42348. BABYLON.serializeAsColor3("reflectivity"),
  42349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42350. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42351. __decorate([
  42352. BABYLON.serializeAsColor3("reflection"),
  42353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42354. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42355. __decorate([
  42356. BABYLON.serializeAsColor3("emissive"),
  42357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42358. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42359. __decorate([
  42360. BABYLON.serialize(),
  42361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42362. ], PBRMaterial.prototype, "microSurface", void 0);
  42363. __decorate([
  42364. BABYLON.serialize(),
  42365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42366. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42367. __decorate([
  42368. BABYLON.serialize(),
  42369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42370. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42371. __decorate([
  42372. BABYLON.serialize(),
  42373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42374. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42375. __decorate([
  42376. BABYLON.serialize(),
  42377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42378. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42379. __decorate([
  42380. BABYLON.serialize(),
  42381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42382. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42383. __decorate([
  42384. BABYLON.serialize(),
  42385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42386. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42387. __decorate([
  42388. BABYLON.serialize(),
  42389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42390. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42391. __decorate([
  42392. BABYLON.serialize(),
  42393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42394. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42395. __decorate([
  42396. BABYLON.serialize(),
  42397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42398. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42399. __decorate([
  42400. BABYLON.serialize(),
  42401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42402. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42403. __decorate([
  42404. BABYLON.serialize(),
  42405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42406. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42407. __decorate([
  42408. BABYLON.serialize(),
  42409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42410. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42411. __decorate([
  42412. BABYLON.serialize(),
  42413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42414. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42415. __decorate([
  42416. BABYLON.serialize(),
  42417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42418. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42419. __decorate([
  42420. BABYLON.serialize(),
  42421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42422. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42423. __decorate([
  42424. BABYLON.serialize(),
  42425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42426. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42427. __decorate([
  42428. BABYLON.serialize(),
  42429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42430. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42431. __decorate([
  42432. BABYLON.serialize(),
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42434. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42435. __decorate([
  42436. BABYLON.serialize(),
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42438. ], PBRMaterial.prototype, "useParallax", void 0);
  42439. __decorate([
  42440. BABYLON.serialize(),
  42441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42442. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42443. __decorate([
  42444. BABYLON.serialize(),
  42445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42446. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42447. __decorate([
  42448. BABYLON.serialize(),
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42450. ], PBRMaterial.prototype, "disableLighting", void 0);
  42451. __decorate([
  42452. BABYLON.serialize(),
  42453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42454. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42455. __decorate([
  42456. BABYLON.serialize(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42458. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42459. __decorate([
  42460. BABYLON.serialize(),
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42462. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42463. __decorate([
  42464. BABYLON.serialize(),
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42466. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42467. __decorate([
  42468. BABYLON.serialize(),
  42469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42470. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42471. __decorate([
  42472. BABYLON.serialize(),
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42475. __decorate([
  42476. BABYLON.serialize(),
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42478. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture(),
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42482. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42483. __decorate([
  42484. BABYLON.serialize(),
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42486. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42487. __decorate([
  42488. BABYLON.serialize(),
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42490. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42491. __decorate([
  42492. BABYLON.serialize(),
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42495. return PBRMaterial;
  42496. }(BABYLON.PBRBaseMaterial));
  42497. BABYLON.PBRMaterial = PBRMaterial;
  42498. })(BABYLON || (BABYLON = {}));
  42499. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42500. var BABYLON;
  42501. (function (BABYLON) {
  42502. /**
  42503. * The PBR material of BJS following the metal roughness convention.
  42504. *
  42505. * This fits to the PBR convention in the GLTF definition:
  42506. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42507. */
  42508. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42509. __extends(PBRMetallicRoughnessMaterial, _super);
  42510. /**
  42511. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42512. *
  42513. * @param name The material name
  42514. * @param scene The scene the material will be use in.
  42515. */
  42516. function PBRMetallicRoughnessMaterial(name, scene) {
  42517. var _this = _super.call(this, name, scene) || this;
  42518. _this._useRoughnessFromMetallicTextureAlpha = false;
  42519. _this._useRoughnessFromMetallicTextureGreen = true;
  42520. _this._useMetallnessFromMetallicTextureBlue = true;
  42521. _this._forceMetallicWorkflow = true;
  42522. return _this;
  42523. }
  42524. /**
  42525. * Return the currrent class name of the material.
  42526. */
  42527. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42528. return "PBRMetallicRoughnessMaterial";
  42529. };
  42530. /**
  42531. * Return the active textures of the material.
  42532. */
  42533. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42534. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42535. if (this.baseTexture) {
  42536. activeTextures.push(this.baseTexture);
  42537. }
  42538. if (this.metallicRoughnessTexture) {
  42539. activeTextures.push(this.metallicRoughnessTexture);
  42540. }
  42541. return activeTextures;
  42542. };
  42543. /**
  42544. * Checks to see if a texture is used in the material.
  42545. * @param texture - Base texture to use.
  42546. * @returns - Boolean specifying if a texture is used in the material.
  42547. */
  42548. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42549. if (_super.prototype.hasTexture.call(this, texture)) {
  42550. return true;
  42551. }
  42552. if (this.baseTexture === texture) {
  42553. return true;
  42554. }
  42555. if (this.metallicRoughnessTexture === texture) {
  42556. return true;
  42557. }
  42558. return false;
  42559. };
  42560. /**
  42561. * Makes a duplicate of the current material.
  42562. * @param name - name to use for the new material.
  42563. */
  42564. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42565. var _this = this;
  42566. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42567. clone.id = name;
  42568. clone.name = name;
  42569. return clone;
  42570. };
  42571. /**
  42572. * Serialize the material to a parsable JSON object.
  42573. */
  42574. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42575. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42576. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42577. return serializationObject;
  42578. };
  42579. /**
  42580. * Parses a JSON object correponding to the serialize function.
  42581. */
  42582. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42583. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42584. };
  42585. __decorate([
  42586. BABYLON.serializeAsColor3(),
  42587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42588. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42589. __decorate([
  42590. BABYLON.serializeAsTexture(),
  42591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42592. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42593. __decorate([
  42594. BABYLON.serialize(),
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42596. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42597. __decorate([
  42598. BABYLON.serialize(),
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42600. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42601. __decorate([
  42602. BABYLON.serializeAsTexture(),
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42604. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42605. return PBRMetallicRoughnessMaterial;
  42606. }(BABYLON.PBRBaseSimpleMaterial));
  42607. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42608. })(BABYLON || (BABYLON = {}));
  42609. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42610. var BABYLON;
  42611. (function (BABYLON) {
  42612. /**
  42613. * The PBR material of BJS following the specular glossiness convention.
  42614. *
  42615. * This fits to the PBR convention in the GLTF definition:
  42616. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42617. */
  42618. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42619. __extends(PBRSpecularGlossinessMaterial, _super);
  42620. /**
  42621. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42622. *
  42623. * @param name The material name
  42624. * @param scene The scene the material will be use in.
  42625. */
  42626. function PBRSpecularGlossinessMaterial(name, scene) {
  42627. var _this = _super.call(this, name, scene) || this;
  42628. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42629. return _this;
  42630. }
  42631. /**
  42632. * Return the currrent class name of the material.
  42633. */
  42634. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42635. return "PBRSpecularGlossinessMaterial";
  42636. };
  42637. /**
  42638. * Return the active textures of the material.
  42639. */
  42640. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42641. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42642. if (this.diffuseTexture) {
  42643. activeTextures.push(this.diffuseTexture);
  42644. }
  42645. if (this.specularGlossinessTexture) {
  42646. activeTextures.push(this.specularGlossinessTexture);
  42647. }
  42648. return activeTextures;
  42649. };
  42650. /**
  42651. * Checks to see if a texture is used in the material.
  42652. * @param texture - Base texture to use.
  42653. * @returns - Boolean specifying if a texture is used in the material.
  42654. */
  42655. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42656. if (_super.prototype.hasTexture.call(this, texture)) {
  42657. return true;
  42658. }
  42659. if (this.diffuseTexture === texture) {
  42660. return true;
  42661. }
  42662. if (this.specularGlossinessTexture === texture) {
  42663. return true;
  42664. }
  42665. return false;
  42666. };
  42667. /**
  42668. * Makes a duplicate of the current material.
  42669. * @param name - name to use for the new material.
  42670. */
  42671. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42672. var _this = this;
  42673. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42674. clone.id = name;
  42675. clone.name = name;
  42676. return clone;
  42677. };
  42678. /**
  42679. * Serialize the material to a parsable JSON object.
  42680. */
  42681. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42682. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42683. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42684. return serializationObject;
  42685. };
  42686. /**
  42687. * Parses a JSON object correponding to the serialize function.
  42688. */
  42689. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42690. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42691. };
  42692. __decorate([
  42693. BABYLON.serializeAsColor3("diffuse"),
  42694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42695. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42696. __decorate([
  42697. BABYLON.serializeAsTexture(),
  42698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42699. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42700. __decorate([
  42701. BABYLON.serializeAsColor3("specular"),
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42703. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42704. __decorate([
  42705. BABYLON.serialize(),
  42706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42707. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42708. __decorate([
  42709. BABYLON.serializeAsTexture(),
  42710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42711. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42712. return PBRSpecularGlossinessMaterial;
  42713. }(BABYLON.PBRBaseSimpleMaterial));
  42714. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42715. })(BABYLON || (BABYLON = {}));
  42716. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42717. var BABYLON;
  42718. (function (BABYLON) {
  42719. BABYLON.CameraInputTypes = {};
  42720. var CameraInputsManager = /** @class */ (function () {
  42721. function CameraInputsManager(camera) {
  42722. this.attached = {};
  42723. this.camera = camera;
  42724. this.checkInputs = function () { };
  42725. }
  42726. /**
  42727. * Add an input method to a camera.
  42728. * builtin inputs example: camera.inputs.addGamepad();
  42729. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42730. * @param input camera input method
  42731. */
  42732. CameraInputsManager.prototype.add = function (input) {
  42733. var type = input.getSimpleName();
  42734. if (this.attached[type]) {
  42735. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42736. return;
  42737. }
  42738. this.attached[type] = input;
  42739. input.camera = this.camera;
  42740. //for checkInputs, we are dynamically creating a function
  42741. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42742. if (input.checkInputs) {
  42743. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42744. }
  42745. if (this.attachedElement) {
  42746. input.attachControl(this.attachedElement);
  42747. }
  42748. };
  42749. /**
  42750. * Remove a specific input method from a camera
  42751. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42752. * @param inputToRemove camera input method
  42753. */
  42754. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42755. for (var cam in this.attached) {
  42756. var input = this.attached[cam];
  42757. if (input === inputToRemove) {
  42758. input.detachControl(this.attachedElement);
  42759. input.camera = null;
  42760. delete this.attached[cam];
  42761. this.rebuildInputCheck();
  42762. }
  42763. }
  42764. };
  42765. CameraInputsManager.prototype.removeByType = function (inputType) {
  42766. for (var cam in this.attached) {
  42767. var input = this.attached[cam];
  42768. if (input.getClassName() === inputType) {
  42769. input.detachControl(this.attachedElement);
  42770. input.camera = null;
  42771. delete this.attached[cam];
  42772. this.rebuildInputCheck();
  42773. }
  42774. }
  42775. };
  42776. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42777. var current = this.checkInputs;
  42778. return function () {
  42779. current();
  42780. fn();
  42781. };
  42782. };
  42783. CameraInputsManager.prototype.attachInput = function (input) {
  42784. if (this.attachedElement) {
  42785. input.attachControl(this.attachedElement, this.noPreventDefault);
  42786. }
  42787. };
  42788. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42789. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42790. if (this.attachedElement) {
  42791. return;
  42792. }
  42793. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42794. this.attachedElement = element;
  42795. this.noPreventDefault = noPreventDefault;
  42796. for (var cam in this.attached) {
  42797. this.attached[cam].attachControl(element, noPreventDefault);
  42798. }
  42799. };
  42800. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42801. if (disconnect === void 0) { disconnect = false; }
  42802. if (this.attachedElement !== element) {
  42803. return;
  42804. }
  42805. for (var cam in this.attached) {
  42806. this.attached[cam].detachControl(element);
  42807. if (disconnect) {
  42808. this.attached[cam].camera = null;
  42809. }
  42810. }
  42811. this.attachedElement = null;
  42812. };
  42813. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42814. this.checkInputs = function () { };
  42815. for (var cam in this.attached) {
  42816. var input = this.attached[cam];
  42817. if (input.checkInputs) {
  42818. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42819. }
  42820. }
  42821. };
  42822. /**
  42823. * Remove all attached input methods from a camera
  42824. */
  42825. CameraInputsManager.prototype.clear = function () {
  42826. if (this.attachedElement) {
  42827. this.detachElement(this.attachedElement, true);
  42828. }
  42829. this.attached = {};
  42830. this.attachedElement = null;
  42831. this.checkInputs = function () { };
  42832. };
  42833. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42834. var inputs = {};
  42835. for (var cam in this.attached) {
  42836. var input = this.attached[cam];
  42837. var res = BABYLON.SerializationHelper.Serialize(input);
  42838. inputs[input.getClassName()] = res;
  42839. }
  42840. serializedCamera.inputsmgr = inputs;
  42841. };
  42842. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42843. var parsedInputs = parsedCamera.inputsmgr;
  42844. if (parsedInputs) {
  42845. this.clear();
  42846. for (var n in parsedInputs) {
  42847. var construct = BABYLON.CameraInputTypes[n];
  42848. if (construct) {
  42849. var parsedinput = parsedInputs[n];
  42850. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42851. this.add(input);
  42852. }
  42853. }
  42854. }
  42855. else {
  42856. //2016-03-08 this part is for managing backward compatibility
  42857. for (var n in this.attached) {
  42858. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42859. if (construct) {
  42860. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42861. this.remove(this.attached[n]);
  42862. this.add(input);
  42863. }
  42864. }
  42865. }
  42866. };
  42867. return CameraInputsManager;
  42868. }());
  42869. BABYLON.CameraInputsManager = CameraInputsManager;
  42870. })(BABYLON || (BABYLON = {}));
  42871. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42872. var BABYLON;
  42873. (function (BABYLON) {
  42874. var TargetCamera = /** @class */ (function (_super) {
  42875. __extends(TargetCamera, _super);
  42876. function TargetCamera(name, position, scene) {
  42877. var _this = _super.call(this, name, position, scene) || this;
  42878. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42879. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42880. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42881. _this.speed = 2.0;
  42882. _this.noRotationConstraint = false;
  42883. _this.lockedTarget = null;
  42884. _this._currentTarget = BABYLON.Vector3.Zero();
  42885. _this._viewMatrix = BABYLON.Matrix.Zero();
  42886. _this._camMatrix = BABYLON.Matrix.Zero();
  42887. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42888. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42889. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42890. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42891. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42892. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42893. _this._tempMatrix = BABYLON.Matrix.Zero();
  42894. return _this;
  42895. }
  42896. TargetCamera.prototype.getFrontPosition = function (distance) {
  42897. this.getWorldMatrix();
  42898. var direction = this.getTarget().subtract(this.position);
  42899. direction.normalize();
  42900. direction.scaleInPlace(distance);
  42901. return this.globalPosition.add(direction);
  42902. };
  42903. TargetCamera.prototype._getLockedTargetPosition = function () {
  42904. if (!this.lockedTarget) {
  42905. return null;
  42906. }
  42907. if (this.lockedTarget.absolutePosition) {
  42908. this.lockedTarget.computeWorldMatrix();
  42909. }
  42910. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42911. };
  42912. TargetCamera.prototype.storeState = function () {
  42913. this._storedPosition = this.position.clone();
  42914. this._storedRotation = this.rotation.clone();
  42915. if (this.rotationQuaternion) {
  42916. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42917. }
  42918. return _super.prototype.storeState.call(this);
  42919. };
  42920. /**
  42921. * Restored camera state. You must call storeState() first
  42922. */
  42923. TargetCamera.prototype._restoreStateValues = function () {
  42924. if (!_super.prototype._restoreStateValues.call(this)) {
  42925. return false;
  42926. }
  42927. this.position = this._storedPosition.clone();
  42928. this.rotation = this._storedRotation.clone();
  42929. if (this.rotationQuaternion) {
  42930. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42931. }
  42932. this.cameraDirection.copyFromFloats(0, 0, 0);
  42933. this.cameraRotation.copyFromFloats(0, 0);
  42934. return true;
  42935. };
  42936. // Cache
  42937. TargetCamera.prototype._initCache = function () {
  42938. _super.prototype._initCache.call(this);
  42939. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42940. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42941. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42942. };
  42943. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42944. if (!ignoreParentClass) {
  42945. _super.prototype._updateCache.call(this);
  42946. }
  42947. var lockedTargetPosition = this._getLockedTargetPosition();
  42948. if (!lockedTargetPosition) {
  42949. this._cache.lockedTarget = null;
  42950. }
  42951. else {
  42952. if (!this._cache.lockedTarget) {
  42953. this._cache.lockedTarget = lockedTargetPosition.clone();
  42954. }
  42955. else {
  42956. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42957. }
  42958. }
  42959. this._cache.rotation.copyFrom(this.rotation);
  42960. if (this.rotationQuaternion)
  42961. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42962. };
  42963. // Synchronized
  42964. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42965. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42966. return false;
  42967. }
  42968. var lockedTargetPosition = this._getLockedTargetPosition();
  42969. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42970. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42971. };
  42972. // Methods
  42973. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42974. var engine = this.getEngine();
  42975. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42976. };
  42977. // Target
  42978. TargetCamera.prototype.setTarget = function (target) {
  42979. this.upVector.normalize();
  42980. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42981. this._camMatrix.invert();
  42982. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42983. var vDir = target.subtract(this.position);
  42984. if (vDir.x >= 0.0) {
  42985. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42986. }
  42987. else {
  42988. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42989. }
  42990. this.rotation.z = 0;
  42991. if (isNaN(this.rotation.x)) {
  42992. this.rotation.x = 0;
  42993. }
  42994. if (isNaN(this.rotation.y)) {
  42995. this.rotation.y = 0;
  42996. }
  42997. if (isNaN(this.rotation.z)) {
  42998. this.rotation.z = 0;
  42999. }
  43000. if (this.rotationQuaternion) {
  43001. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43002. }
  43003. };
  43004. /**
  43005. * Return the current target position of the camera. This value is expressed in local space.
  43006. */
  43007. TargetCamera.prototype.getTarget = function () {
  43008. return this._currentTarget;
  43009. };
  43010. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43011. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43012. };
  43013. TargetCamera.prototype._updatePosition = function () {
  43014. if (this.parent) {
  43015. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43016. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43017. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43018. return;
  43019. }
  43020. this.position.addInPlace(this.cameraDirection);
  43021. };
  43022. TargetCamera.prototype._checkInputs = function () {
  43023. var needToMove = this._decideIfNeedsToMove();
  43024. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43025. // Move
  43026. if (needToMove) {
  43027. this._updatePosition();
  43028. }
  43029. // Rotate
  43030. if (needToRotate) {
  43031. this.rotation.x += this.cameraRotation.x;
  43032. this.rotation.y += this.cameraRotation.y;
  43033. //rotate, if quaternion is set and rotation was used
  43034. if (this.rotationQuaternion) {
  43035. var len = this.rotation.lengthSquared();
  43036. if (len) {
  43037. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43038. }
  43039. }
  43040. if (!this.noRotationConstraint) {
  43041. var limit = (Math.PI / 2) * 0.95;
  43042. if (this.rotation.x > limit)
  43043. this.rotation.x = limit;
  43044. if (this.rotation.x < -limit)
  43045. this.rotation.x = -limit;
  43046. }
  43047. }
  43048. // Inertia
  43049. if (needToMove) {
  43050. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43051. this.cameraDirection.x = 0;
  43052. }
  43053. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43054. this.cameraDirection.y = 0;
  43055. }
  43056. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43057. this.cameraDirection.z = 0;
  43058. }
  43059. this.cameraDirection.scaleInPlace(this.inertia);
  43060. }
  43061. if (needToRotate) {
  43062. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43063. this.cameraRotation.x = 0;
  43064. }
  43065. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43066. this.cameraRotation.y = 0;
  43067. }
  43068. this.cameraRotation.scaleInPlace(this.inertia);
  43069. }
  43070. _super.prototype._checkInputs.call(this);
  43071. };
  43072. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43073. if (this.rotationQuaternion) {
  43074. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43075. }
  43076. else {
  43077. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43078. }
  43079. //update the up vector!
  43080. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43081. };
  43082. TargetCamera.prototype._getViewMatrix = function () {
  43083. if (this.lockedTarget) {
  43084. this.setTarget(this._getLockedTargetPosition());
  43085. }
  43086. // Compute
  43087. this._updateCameraRotationMatrix();
  43088. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43089. // Computing target and final matrix
  43090. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43091. if (this.getScene().useRightHandedSystem) {
  43092. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43093. }
  43094. else {
  43095. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43096. }
  43097. return this._viewMatrix;
  43098. };
  43099. /**
  43100. * @override
  43101. * Override Camera.createRigCamera
  43102. */
  43103. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43104. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43105. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43106. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43107. if (!this.rotationQuaternion) {
  43108. this.rotationQuaternion = new BABYLON.Quaternion();
  43109. }
  43110. rigCamera._cameraRigParams = {};
  43111. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43112. }
  43113. return rigCamera;
  43114. }
  43115. return null;
  43116. };
  43117. /**
  43118. * @override
  43119. * Override Camera._updateRigCameras
  43120. */
  43121. TargetCamera.prototype._updateRigCameras = function () {
  43122. var camLeft = this._rigCameras[0];
  43123. var camRight = this._rigCameras[1];
  43124. switch (this.cameraRigMode) {
  43125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43126. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43127. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43129. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43130. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43131. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43132. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43133. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43134. camLeft.setTarget(this.getTarget());
  43135. camRight.setTarget(this.getTarget());
  43136. break;
  43137. case BABYLON.Camera.RIG_MODE_VR:
  43138. if (camLeft.rotationQuaternion) {
  43139. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43140. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43141. }
  43142. else {
  43143. camLeft.rotation.copyFrom(this.rotation);
  43144. camRight.rotation.copyFrom(this.rotation);
  43145. }
  43146. camLeft.position.copyFrom(this.position);
  43147. camRight.position.copyFrom(this.position);
  43148. break;
  43149. }
  43150. _super.prototype._updateRigCameras.call(this);
  43151. };
  43152. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43153. if (!this._rigCamTransformMatrix) {
  43154. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43155. }
  43156. var target = this.getTarget();
  43157. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43158. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43160. };
  43161. TargetCamera.prototype.getClassName = function () {
  43162. return "TargetCamera";
  43163. };
  43164. __decorate([
  43165. BABYLON.serializeAsVector3()
  43166. ], TargetCamera.prototype, "rotation", void 0);
  43167. __decorate([
  43168. BABYLON.serialize()
  43169. ], TargetCamera.prototype, "speed", void 0);
  43170. __decorate([
  43171. BABYLON.serializeAsMeshReference("lockedTargetId")
  43172. ], TargetCamera.prototype, "lockedTarget", void 0);
  43173. return TargetCamera;
  43174. }(BABYLON.Camera));
  43175. BABYLON.TargetCamera = TargetCamera;
  43176. })(BABYLON || (BABYLON = {}));
  43177. //# sourceMappingURL=babylon.targetCamera.js.map
  43178. var BABYLON;
  43179. (function (BABYLON) {
  43180. var FreeCameraMouseInput = /** @class */ (function () {
  43181. function FreeCameraMouseInput(touchEnabled) {
  43182. if (touchEnabled === void 0) { touchEnabled = true; }
  43183. this.touchEnabled = touchEnabled;
  43184. this.buttons = [0, 1, 2];
  43185. this.angularSensibility = 2000.0;
  43186. this.previousPosition = null;
  43187. }
  43188. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43189. var _this = this;
  43190. var engine = this.camera.getEngine();
  43191. if (!this._pointerInput) {
  43192. this._pointerInput = function (p, s) {
  43193. var evt = p.event;
  43194. if (engine.isInVRExclusivePointerMode) {
  43195. return;
  43196. }
  43197. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43198. return;
  43199. }
  43200. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43201. return;
  43202. }
  43203. var srcElement = (evt.srcElement || evt.target);
  43204. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43205. try {
  43206. srcElement.setPointerCapture(evt.pointerId);
  43207. }
  43208. catch (e) {
  43209. //Nothing to do with the error. Execution will continue.
  43210. }
  43211. _this.previousPosition = {
  43212. x: evt.clientX,
  43213. y: evt.clientY
  43214. };
  43215. if (!noPreventDefault) {
  43216. evt.preventDefault();
  43217. element.focus();
  43218. }
  43219. }
  43220. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43221. try {
  43222. srcElement.releasePointerCapture(evt.pointerId);
  43223. }
  43224. catch (e) {
  43225. //Nothing to do with the error.
  43226. }
  43227. _this.previousPosition = null;
  43228. if (!noPreventDefault) {
  43229. evt.preventDefault();
  43230. }
  43231. }
  43232. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43233. if (!_this.previousPosition || engine.isPointerLock) {
  43234. return;
  43235. }
  43236. var offsetX = evt.clientX - _this.previousPosition.x;
  43237. var offsetY = evt.clientY - _this.previousPosition.y;
  43238. if (_this.camera.getScene().useRightHandedSystem) {
  43239. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43240. }
  43241. else {
  43242. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43243. }
  43244. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43245. _this.previousPosition = {
  43246. x: evt.clientX,
  43247. y: evt.clientY
  43248. };
  43249. if (!noPreventDefault) {
  43250. evt.preventDefault();
  43251. }
  43252. }
  43253. };
  43254. }
  43255. this._onMouseMove = function (evt) {
  43256. if (!engine.isPointerLock) {
  43257. return;
  43258. }
  43259. if (engine.isInVRExclusivePointerMode) {
  43260. return;
  43261. }
  43262. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43263. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43264. if (_this.camera.getScene().useRightHandedSystem) {
  43265. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43266. }
  43267. else {
  43268. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43269. }
  43270. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43271. _this.previousPosition = null;
  43272. if (!noPreventDefault) {
  43273. evt.preventDefault();
  43274. }
  43275. };
  43276. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43277. element.addEventListener("mousemove", this._onMouseMove, false);
  43278. };
  43279. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43280. if (this._observer && element) {
  43281. this.camera.getScene().onPointerObservable.remove(this._observer);
  43282. if (this._onMouseMove) {
  43283. element.removeEventListener("mousemove", this._onMouseMove);
  43284. }
  43285. this._observer = null;
  43286. this._onMouseMove = null;
  43287. this.previousPosition = null;
  43288. }
  43289. };
  43290. FreeCameraMouseInput.prototype.getClassName = function () {
  43291. return "FreeCameraMouseInput";
  43292. };
  43293. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43294. return "mouse";
  43295. };
  43296. __decorate([
  43297. BABYLON.serialize()
  43298. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43299. __decorate([
  43300. BABYLON.serialize()
  43301. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43302. return FreeCameraMouseInput;
  43303. }());
  43304. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43305. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43306. })(BABYLON || (BABYLON = {}));
  43307. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43308. var BABYLON;
  43309. (function (BABYLON) {
  43310. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43311. function FreeCameraKeyboardMoveInput() {
  43312. this._keys = new Array();
  43313. this.keysUp = [38];
  43314. this.keysDown = [40];
  43315. this.keysLeft = [37];
  43316. this.keysRight = [39];
  43317. }
  43318. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43319. var _this = this;
  43320. if (this._onCanvasBlurObserver) {
  43321. return;
  43322. }
  43323. this._scene = this.camera.getScene();
  43324. this._engine = this._scene.getEngine();
  43325. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43326. _this._keys = [];
  43327. });
  43328. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43329. var evt = info.event;
  43330. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43331. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43332. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43333. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43334. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43335. var index = _this._keys.indexOf(evt.keyCode);
  43336. if (index === -1) {
  43337. _this._keys.push(evt.keyCode);
  43338. }
  43339. if (!noPreventDefault) {
  43340. evt.preventDefault();
  43341. }
  43342. }
  43343. }
  43344. else {
  43345. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43346. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43347. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43348. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43349. var index = _this._keys.indexOf(evt.keyCode);
  43350. if (index >= 0) {
  43351. _this._keys.splice(index, 1);
  43352. }
  43353. if (!noPreventDefault) {
  43354. evt.preventDefault();
  43355. }
  43356. }
  43357. }
  43358. });
  43359. };
  43360. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43361. if (this._scene) {
  43362. if (this._onKeyboardObserver) {
  43363. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43364. }
  43365. if (this._onCanvasBlurObserver) {
  43366. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43367. }
  43368. this._onKeyboardObserver = null;
  43369. this._onCanvasBlurObserver = null;
  43370. }
  43371. this._keys = [];
  43372. };
  43373. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43374. if (this._onKeyboardObserver) {
  43375. var camera = this.camera;
  43376. // Keyboard
  43377. for (var index = 0; index < this._keys.length; index++) {
  43378. var keyCode = this._keys[index];
  43379. var speed = camera._computeLocalCameraSpeed();
  43380. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43381. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43382. }
  43383. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43384. camera._localDirection.copyFromFloats(0, 0, speed);
  43385. }
  43386. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43387. camera._localDirection.copyFromFloats(speed, 0, 0);
  43388. }
  43389. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43390. camera._localDirection.copyFromFloats(0, 0, -speed);
  43391. }
  43392. if (camera.getScene().useRightHandedSystem) {
  43393. camera._localDirection.z *= -1;
  43394. }
  43395. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43396. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43397. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43398. }
  43399. }
  43400. };
  43401. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43402. return "FreeCameraKeyboardMoveInput";
  43403. };
  43404. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43405. this._keys = [];
  43406. };
  43407. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43408. return "keyboard";
  43409. };
  43410. __decorate([
  43411. BABYLON.serialize()
  43412. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43413. __decorate([
  43414. BABYLON.serialize()
  43415. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43416. __decorate([
  43417. BABYLON.serialize()
  43418. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43419. __decorate([
  43420. BABYLON.serialize()
  43421. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43422. return FreeCameraKeyboardMoveInput;
  43423. }());
  43424. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43425. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43426. })(BABYLON || (BABYLON = {}));
  43427. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43428. var BABYLON;
  43429. (function (BABYLON) {
  43430. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43431. __extends(FreeCameraInputsManager, _super);
  43432. function FreeCameraInputsManager(camera) {
  43433. return _super.call(this, camera) || this;
  43434. }
  43435. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43436. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43437. return this;
  43438. };
  43439. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43440. if (touchEnabled === void 0) { touchEnabled = true; }
  43441. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43442. return this;
  43443. };
  43444. FreeCameraInputsManager.prototype.addGamepad = function () {
  43445. this.add(new BABYLON.FreeCameraGamepadInput());
  43446. return this;
  43447. };
  43448. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43449. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43450. return this;
  43451. };
  43452. FreeCameraInputsManager.prototype.addTouch = function () {
  43453. this.add(new BABYLON.FreeCameraTouchInput());
  43454. return this;
  43455. };
  43456. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43457. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43458. return this;
  43459. };
  43460. return FreeCameraInputsManager;
  43461. }(BABYLON.CameraInputsManager));
  43462. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43463. })(BABYLON || (BABYLON = {}));
  43464. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43465. var BABYLON;
  43466. (function (BABYLON) {
  43467. var FreeCamera = /** @class */ (function (_super) {
  43468. __extends(FreeCamera, _super);
  43469. function FreeCamera(name, position, scene) {
  43470. var _this = _super.call(this, name, position, scene) || this;
  43471. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43472. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43473. _this.checkCollisions = false;
  43474. _this.applyGravity = false;
  43475. _this._needMoveForGravity = false;
  43476. _this._oldPosition = BABYLON.Vector3.Zero();
  43477. _this._diffPosition = BABYLON.Vector3.Zero();
  43478. _this._newPosition = BABYLON.Vector3.Zero();
  43479. // Collisions
  43480. _this._collisionMask = -1;
  43481. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43482. if (collidedMesh === void 0) { collidedMesh = null; }
  43483. //TODO move this to the collision coordinator!
  43484. if (_this.getScene().workerCollisions)
  43485. newPosition.multiplyInPlace(_this._collider._radius);
  43486. var updatePosition = function (newPos) {
  43487. _this._newPosition.copyFrom(newPos);
  43488. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43489. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43490. _this.position.addInPlace(_this._diffPosition);
  43491. if (_this.onCollide && collidedMesh) {
  43492. _this.onCollide(collidedMesh);
  43493. }
  43494. }
  43495. };
  43496. updatePosition(newPosition);
  43497. };
  43498. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43499. _this.inputs.addKeyboard().addMouse();
  43500. return _this;
  43501. }
  43502. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43503. //-- begin properties for backward compatibility for inputs
  43504. /**
  43505. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43506. * Higher values reduce sensitivity.
  43507. */
  43508. get: function () {
  43509. var mouse = this.inputs.attached["mouse"];
  43510. if (mouse)
  43511. return mouse.angularSensibility;
  43512. return 0;
  43513. },
  43514. /**
  43515. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43516. * Higher values reduce sensitivity.
  43517. */
  43518. set: function (value) {
  43519. var mouse = this.inputs.attached["mouse"];
  43520. if (mouse)
  43521. mouse.angularSensibility = value;
  43522. },
  43523. enumerable: true,
  43524. configurable: true
  43525. });
  43526. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43527. get: function () {
  43528. var keyboard = this.inputs.attached["keyboard"];
  43529. if (keyboard)
  43530. return keyboard.keysUp;
  43531. return [];
  43532. },
  43533. set: function (value) {
  43534. var keyboard = this.inputs.attached["keyboard"];
  43535. if (keyboard)
  43536. keyboard.keysUp = value;
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43542. get: function () {
  43543. var keyboard = this.inputs.attached["keyboard"];
  43544. if (keyboard)
  43545. return keyboard.keysDown;
  43546. return [];
  43547. },
  43548. set: function (value) {
  43549. var keyboard = this.inputs.attached["keyboard"];
  43550. if (keyboard)
  43551. keyboard.keysDown = value;
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43557. get: function () {
  43558. var keyboard = this.inputs.attached["keyboard"];
  43559. if (keyboard)
  43560. return keyboard.keysLeft;
  43561. return [];
  43562. },
  43563. set: function (value) {
  43564. var keyboard = this.inputs.attached["keyboard"];
  43565. if (keyboard)
  43566. keyboard.keysLeft = value;
  43567. },
  43568. enumerable: true,
  43569. configurable: true
  43570. });
  43571. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43572. get: function () {
  43573. var keyboard = this.inputs.attached["keyboard"];
  43574. if (keyboard)
  43575. return keyboard.keysRight;
  43576. return [];
  43577. },
  43578. set: function (value) {
  43579. var keyboard = this.inputs.attached["keyboard"];
  43580. if (keyboard)
  43581. keyboard.keysRight = value;
  43582. },
  43583. enumerable: true,
  43584. configurable: true
  43585. });
  43586. // Controls
  43587. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43588. this.inputs.attachElement(element, noPreventDefault);
  43589. };
  43590. FreeCamera.prototype.detachControl = function (element) {
  43591. this.inputs.detachElement(element);
  43592. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43593. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43594. };
  43595. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43596. get: function () {
  43597. return this._collisionMask;
  43598. },
  43599. set: function (mask) {
  43600. this._collisionMask = !isNaN(mask) ? mask : -1;
  43601. },
  43602. enumerable: true,
  43603. configurable: true
  43604. });
  43605. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43606. var globalPosition;
  43607. if (this.parent) {
  43608. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43609. }
  43610. else {
  43611. globalPosition = this.position;
  43612. }
  43613. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43614. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43615. if (!this._collider) {
  43616. this._collider = new BABYLON.Collider();
  43617. }
  43618. this._collider._radius = this.ellipsoid;
  43619. this._collider.collisionMask = this._collisionMask;
  43620. //no need for clone, as long as gravity is not on.
  43621. var actualDisplacement = displacement;
  43622. //add gravity to the direction to prevent the dual-collision checking
  43623. if (this.applyGravity) {
  43624. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43625. actualDisplacement = displacement.add(this.getScene().gravity);
  43626. }
  43627. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43628. };
  43629. FreeCamera.prototype._checkInputs = function () {
  43630. if (!this._localDirection) {
  43631. this._localDirection = BABYLON.Vector3.Zero();
  43632. this._transformedDirection = BABYLON.Vector3.Zero();
  43633. }
  43634. this.inputs.checkInputs();
  43635. _super.prototype._checkInputs.call(this);
  43636. };
  43637. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43638. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43639. };
  43640. FreeCamera.prototype._updatePosition = function () {
  43641. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43642. this._collideWithWorld(this.cameraDirection);
  43643. }
  43644. else {
  43645. _super.prototype._updatePosition.call(this);
  43646. }
  43647. };
  43648. FreeCamera.prototype.dispose = function () {
  43649. this.inputs.clear();
  43650. _super.prototype.dispose.call(this);
  43651. };
  43652. FreeCamera.prototype.getClassName = function () {
  43653. return "FreeCamera";
  43654. };
  43655. __decorate([
  43656. BABYLON.serializeAsVector3()
  43657. ], FreeCamera.prototype, "ellipsoid", void 0);
  43658. __decorate([
  43659. BABYLON.serializeAsVector3()
  43660. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43661. __decorate([
  43662. BABYLON.serialize()
  43663. ], FreeCamera.prototype, "checkCollisions", void 0);
  43664. __decorate([
  43665. BABYLON.serialize()
  43666. ], FreeCamera.prototype, "applyGravity", void 0);
  43667. return FreeCamera;
  43668. }(BABYLON.TargetCamera));
  43669. BABYLON.FreeCamera = FreeCamera;
  43670. })(BABYLON || (BABYLON = {}));
  43671. //# sourceMappingURL=babylon.freeCamera.js.map
  43672. var BABYLON;
  43673. (function (BABYLON) {
  43674. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43675. function ArcRotateCameraKeyboardMoveInput() {
  43676. this._keys = new Array();
  43677. this.keysUp = [38];
  43678. this.keysDown = [40];
  43679. this.keysLeft = [37];
  43680. this.keysRight = [39];
  43681. this.keysReset = [220];
  43682. this.panningSensibility = 50.0;
  43683. this.zoomingSensibility = 25.0;
  43684. this.useAltToZoom = true;
  43685. }
  43686. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43687. var _this = this;
  43688. if (this._onCanvasBlurObserver) {
  43689. return;
  43690. }
  43691. this._scene = this.camera.getScene();
  43692. this._engine = this._scene.getEngine();
  43693. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43694. _this._keys = [];
  43695. });
  43696. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43697. var evt = info.event;
  43698. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43699. _this._ctrlPressed = evt.ctrlKey;
  43700. _this._altPressed = evt.altKey;
  43701. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43702. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43703. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43704. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43705. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43706. var index = _this._keys.indexOf(evt.keyCode);
  43707. if (index === -1) {
  43708. _this._keys.push(evt.keyCode);
  43709. }
  43710. if (evt.preventDefault) {
  43711. if (!noPreventDefault) {
  43712. evt.preventDefault();
  43713. }
  43714. }
  43715. }
  43716. }
  43717. else {
  43718. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43719. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43720. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43721. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43722. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43723. var index = _this._keys.indexOf(evt.keyCode);
  43724. if (index >= 0) {
  43725. _this._keys.splice(index, 1);
  43726. }
  43727. if (evt.preventDefault) {
  43728. if (!noPreventDefault) {
  43729. evt.preventDefault();
  43730. }
  43731. }
  43732. }
  43733. }
  43734. });
  43735. };
  43736. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43737. if (this._scene) {
  43738. if (this._onKeyboardObserver) {
  43739. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43740. }
  43741. if (this._onCanvasBlurObserver) {
  43742. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43743. }
  43744. this._onKeyboardObserver = null;
  43745. this._onCanvasBlurObserver = null;
  43746. }
  43747. this._keys = [];
  43748. };
  43749. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43750. if (this._onKeyboardObserver) {
  43751. var camera = this.camera;
  43752. for (var index = 0; index < this._keys.length; index++) {
  43753. var keyCode = this._keys[index];
  43754. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43755. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43756. camera.inertialPanningX -= 1 / this.panningSensibility;
  43757. }
  43758. else {
  43759. camera.inertialAlphaOffset -= 0.01;
  43760. }
  43761. }
  43762. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43763. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43764. camera.inertialPanningY += 1 / this.panningSensibility;
  43765. }
  43766. else if (this._altPressed && this.useAltToZoom) {
  43767. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43768. }
  43769. else {
  43770. camera.inertialBetaOffset -= 0.01;
  43771. }
  43772. }
  43773. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43774. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43775. camera.inertialPanningX += 1 / this.panningSensibility;
  43776. }
  43777. else {
  43778. camera.inertialAlphaOffset += 0.01;
  43779. }
  43780. }
  43781. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43782. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43783. camera.inertialPanningY -= 1 / this.panningSensibility;
  43784. }
  43785. else if (this._altPressed && this.useAltToZoom) {
  43786. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43787. }
  43788. else {
  43789. camera.inertialBetaOffset += 0.01;
  43790. }
  43791. }
  43792. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43793. camera.restoreState();
  43794. }
  43795. }
  43796. }
  43797. };
  43798. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43799. return "ArcRotateCameraKeyboardMoveInput";
  43800. };
  43801. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43802. return "keyboard";
  43803. };
  43804. __decorate([
  43805. BABYLON.serialize()
  43806. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43807. __decorate([
  43808. BABYLON.serialize()
  43809. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43810. __decorate([
  43811. BABYLON.serialize()
  43812. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43813. __decorate([
  43814. BABYLON.serialize()
  43815. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43816. __decorate([
  43817. BABYLON.serialize()
  43818. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43819. __decorate([
  43820. BABYLON.serialize()
  43821. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43822. __decorate([
  43823. BABYLON.serialize()
  43824. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43825. __decorate([
  43826. BABYLON.serialize()
  43827. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43828. return ArcRotateCameraKeyboardMoveInput;
  43829. }());
  43830. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43831. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43832. })(BABYLON || (BABYLON = {}));
  43833. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43834. var BABYLON;
  43835. (function (BABYLON) {
  43836. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43837. function ArcRotateCameraMouseWheelInput() {
  43838. this.wheelPrecision = 3.0;
  43839. /**
  43840. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43841. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43842. */
  43843. this.wheelDeltaPercentage = 0;
  43844. }
  43845. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43846. var _this = this;
  43847. this._wheel = function (p, s) {
  43848. //sanity check - this should be a PointerWheel event.
  43849. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43850. return;
  43851. var event = p.event;
  43852. var delta = 0;
  43853. if (event.wheelDelta) {
  43854. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43855. }
  43856. else if (event.detail) {
  43857. delta = -event.detail / _this.wheelPrecision;
  43858. }
  43859. if (delta)
  43860. _this.camera.inertialRadiusOffset += delta;
  43861. if (event.preventDefault) {
  43862. if (!noPreventDefault) {
  43863. event.preventDefault();
  43864. }
  43865. }
  43866. };
  43867. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43868. };
  43869. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43870. if (this._observer && element) {
  43871. this.camera.getScene().onPointerObservable.remove(this._observer);
  43872. this._observer = null;
  43873. this._wheel = null;
  43874. }
  43875. };
  43876. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43877. return "ArcRotateCameraMouseWheelInput";
  43878. };
  43879. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43880. return "mousewheel";
  43881. };
  43882. __decorate([
  43883. BABYLON.serialize()
  43884. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43885. __decorate([
  43886. BABYLON.serialize()
  43887. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43888. return ArcRotateCameraMouseWheelInput;
  43889. }());
  43890. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43891. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43892. })(BABYLON || (BABYLON = {}));
  43893. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43894. var BABYLON;
  43895. (function (BABYLON) {
  43896. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43897. function ArcRotateCameraPointersInput() {
  43898. this.buttons = [0, 1, 2];
  43899. this.angularSensibilityX = 1000.0;
  43900. this.angularSensibilityY = 1000.0;
  43901. this.pinchPrecision = 12.0;
  43902. /**
  43903. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43904. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43905. */
  43906. this.pinchDeltaPercentage = 0;
  43907. this.panningSensibility = 1000.0;
  43908. this.multiTouchPanning = true;
  43909. this.multiTouchPanAndZoom = true;
  43910. this._isPanClick = false;
  43911. this.pinchInwards = true;
  43912. }
  43913. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43914. var _this = this;
  43915. var engine = this.camera.getEngine();
  43916. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43917. var pointA = null;
  43918. var pointB = null;
  43919. var previousPinchSquaredDistance = 0;
  43920. var initialDistance = 0;
  43921. var twoFingerActivityCount = 0;
  43922. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43923. this._pointerInput = function (p, s) {
  43924. var evt = p.event;
  43925. var isTouch = p.event.pointerType === "touch";
  43926. if (engine.isInVRExclusivePointerMode) {
  43927. return;
  43928. }
  43929. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43930. return;
  43931. }
  43932. var srcElement = (evt.srcElement || evt.target);
  43933. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43934. try {
  43935. srcElement.setPointerCapture(evt.pointerId);
  43936. }
  43937. catch (e) {
  43938. //Nothing to do with the error. Execution will continue.
  43939. }
  43940. // Manage panning with pan button click
  43941. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43942. // manage pointers
  43943. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43944. if (pointA === null) {
  43945. pointA = cacheSoloPointer;
  43946. }
  43947. else if (pointB === null) {
  43948. pointB = cacheSoloPointer;
  43949. }
  43950. if (!noPreventDefault) {
  43951. evt.preventDefault();
  43952. element.focus();
  43953. }
  43954. }
  43955. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43956. _this.camera.restoreState();
  43957. }
  43958. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43959. try {
  43960. srcElement.releasePointerCapture(evt.pointerId);
  43961. }
  43962. catch (e) {
  43963. //Nothing to do with the error.
  43964. }
  43965. cacheSoloPointer = null;
  43966. previousPinchSquaredDistance = 0;
  43967. previousMultiTouchPanPosition.isPaning = false;
  43968. previousMultiTouchPanPosition.isPinching = false;
  43969. twoFingerActivityCount = 0;
  43970. initialDistance = 0;
  43971. if (!isTouch) {
  43972. pointB = null; // Mouse and pen are mono pointer
  43973. }
  43974. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43975. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43976. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43977. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43978. if (engine.badOS) {
  43979. pointA = pointB = null;
  43980. }
  43981. else {
  43982. //only remove the impacted pointer in case of multitouch allowing on most
  43983. //platforms switching from rotate to zoom and pan seamlessly.
  43984. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43985. pointA = pointB;
  43986. pointB = null;
  43987. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43988. }
  43989. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43990. pointB = null;
  43991. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43992. }
  43993. else {
  43994. pointA = pointB = null;
  43995. }
  43996. }
  43997. if (!noPreventDefault) {
  43998. evt.preventDefault();
  43999. }
  44000. }
  44001. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44002. if (!noPreventDefault) {
  44003. evt.preventDefault();
  44004. }
  44005. // One button down
  44006. if (pointA && pointB === null && cacheSoloPointer) {
  44007. if (_this.panningSensibility !== 0 &&
  44008. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44009. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44010. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44011. }
  44012. else {
  44013. var offsetX = evt.clientX - cacheSoloPointer.x;
  44014. var offsetY = evt.clientY - cacheSoloPointer.y;
  44015. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44016. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44017. }
  44018. cacheSoloPointer.x = evt.clientX;
  44019. cacheSoloPointer.y = evt.clientY;
  44020. }
  44021. else if (pointA && pointB) {
  44022. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44023. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44024. ed.x = evt.clientX;
  44025. ed.y = evt.clientY;
  44026. var direction = _this.pinchInwards ? 1 : -1;
  44027. var distX = pointA.x - pointB.x;
  44028. var distY = pointA.y - pointB.y;
  44029. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44030. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44031. if (previousPinchSquaredDistance === 0) {
  44032. initialDistance = pinchDistance;
  44033. previousPinchSquaredDistance = pinchSquaredDistance;
  44034. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44035. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44036. return;
  44037. }
  44038. if (_this.multiTouchPanAndZoom) {
  44039. if (_this.pinchDeltaPercentage) {
  44040. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44041. }
  44042. else {
  44043. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44044. (_this.pinchPrecision *
  44045. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44046. direction);
  44047. }
  44048. if (_this.panningSensibility !== 0) {
  44049. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44050. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44051. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44052. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44053. previousMultiTouchPanPosition.x = pointersCenterX;
  44054. previousMultiTouchPanPosition.y = pointersCenterY;
  44055. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44056. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44057. }
  44058. }
  44059. else {
  44060. twoFingerActivityCount++;
  44061. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44062. if (_this.pinchDeltaPercentage) {
  44063. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44064. }
  44065. else {
  44066. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44067. (_this.pinchPrecision *
  44068. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44069. direction);
  44070. }
  44071. previousMultiTouchPanPosition.isPaning = false;
  44072. previousMultiTouchPanPosition.isPinching = true;
  44073. }
  44074. else {
  44075. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44076. if (!previousMultiTouchPanPosition.isPaning) {
  44077. previousMultiTouchPanPosition.isPaning = true;
  44078. previousMultiTouchPanPosition.isPinching = false;
  44079. previousMultiTouchPanPosition.x = ed.x;
  44080. previousMultiTouchPanPosition.y = ed.y;
  44081. return;
  44082. }
  44083. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44084. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44085. }
  44086. }
  44087. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44088. previousMultiTouchPanPosition.x = ed.x;
  44089. previousMultiTouchPanPosition.y = ed.y;
  44090. }
  44091. }
  44092. previousPinchSquaredDistance = pinchSquaredDistance;
  44093. }
  44094. }
  44095. };
  44096. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44097. this._onContextMenu = function (evt) {
  44098. evt.preventDefault();
  44099. };
  44100. if (!this.camera._useCtrlForPanning) {
  44101. element.addEventListener("contextmenu", this._onContextMenu, false);
  44102. }
  44103. this._onLostFocus = function () {
  44104. //this._keys = [];
  44105. pointA = pointB = null;
  44106. previousPinchSquaredDistance = 0;
  44107. previousMultiTouchPanPosition.isPaning = false;
  44108. previousMultiTouchPanPosition.isPinching = false;
  44109. twoFingerActivityCount = 0;
  44110. cacheSoloPointer = null;
  44111. initialDistance = 0;
  44112. };
  44113. this._onMouseMove = function (evt) {
  44114. if (!engine.isPointerLock) {
  44115. return;
  44116. }
  44117. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44118. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44119. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44120. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44121. if (!noPreventDefault) {
  44122. evt.preventDefault();
  44123. }
  44124. };
  44125. this._onGestureStart = function (e) {
  44126. if (window.MSGesture === undefined) {
  44127. return;
  44128. }
  44129. if (!_this._MSGestureHandler) {
  44130. _this._MSGestureHandler = new MSGesture();
  44131. _this._MSGestureHandler.target = element;
  44132. }
  44133. _this._MSGestureHandler.addPointer(e.pointerId);
  44134. };
  44135. this._onGesture = function (e) {
  44136. _this.camera.radius *= e.scale;
  44137. if (e.preventDefault) {
  44138. if (!noPreventDefault) {
  44139. e.stopPropagation();
  44140. e.preventDefault();
  44141. }
  44142. }
  44143. };
  44144. element.addEventListener("mousemove", this._onMouseMove, false);
  44145. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44146. element.addEventListener("MSGestureChange", this._onGesture, false);
  44147. BABYLON.Tools.RegisterTopRootEvents([
  44148. { name: "blur", handler: this._onLostFocus }
  44149. ]);
  44150. };
  44151. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44152. if (this._onLostFocus) {
  44153. BABYLON.Tools.UnregisterTopRootEvents([
  44154. { name: "blur", handler: this._onLostFocus }
  44155. ]);
  44156. }
  44157. if (element && this._observer) {
  44158. this.camera.getScene().onPointerObservable.remove(this._observer);
  44159. this._observer = null;
  44160. if (this._onContextMenu) {
  44161. element.removeEventListener("contextmenu", this._onContextMenu);
  44162. }
  44163. if (this._onMouseMove) {
  44164. element.removeEventListener("mousemove", this._onMouseMove);
  44165. }
  44166. if (this._onGestureStart) {
  44167. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44168. }
  44169. if (this._onGesture) {
  44170. element.removeEventListener("MSGestureChange", this._onGesture);
  44171. }
  44172. this._isPanClick = false;
  44173. this.pinchInwards = true;
  44174. this._onMouseMove = null;
  44175. this._onGestureStart = null;
  44176. this._onGesture = null;
  44177. this._MSGestureHandler = null;
  44178. this._onLostFocus = null;
  44179. this._onContextMenu = null;
  44180. }
  44181. };
  44182. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44183. return "ArcRotateCameraPointersInput";
  44184. };
  44185. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44186. return "pointers";
  44187. };
  44188. __decorate([
  44189. BABYLON.serialize()
  44190. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44191. __decorate([
  44192. BABYLON.serialize()
  44193. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44194. __decorate([
  44195. BABYLON.serialize()
  44196. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44197. __decorate([
  44198. BABYLON.serialize()
  44199. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44200. __decorate([
  44201. BABYLON.serialize()
  44202. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44203. __decorate([
  44204. BABYLON.serialize()
  44205. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44206. __decorate([
  44207. BABYLON.serialize()
  44208. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44209. __decorate([
  44210. BABYLON.serialize()
  44211. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44212. return ArcRotateCameraPointersInput;
  44213. }());
  44214. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44215. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44216. })(BABYLON || (BABYLON = {}));
  44217. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44218. var BABYLON;
  44219. (function (BABYLON) {
  44220. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44221. __extends(ArcRotateCameraInputsManager, _super);
  44222. function ArcRotateCameraInputsManager(camera) {
  44223. return _super.call(this, camera) || this;
  44224. }
  44225. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44226. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44227. return this;
  44228. };
  44229. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44230. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44231. return this;
  44232. };
  44233. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44234. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44235. return this;
  44236. };
  44237. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44238. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44239. return this;
  44240. };
  44241. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44242. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44243. return this;
  44244. };
  44245. return ArcRotateCameraInputsManager;
  44246. }(BABYLON.CameraInputsManager));
  44247. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44248. })(BABYLON || (BABYLON = {}));
  44249. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44250. var BABYLON;
  44251. (function (BABYLON) {
  44252. var ArcRotateCamera = /** @class */ (function (_super) {
  44253. __extends(ArcRotateCamera, _super);
  44254. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44255. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44256. _this.inertialAlphaOffset = 0;
  44257. _this.inertialBetaOffset = 0;
  44258. _this.inertialRadiusOffset = 0;
  44259. _this.lowerAlphaLimit = null;
  44260. _this.upperAlphaLimit = null;
  44261. _this.lowerBetaLimit = 0.01;
  44262. _this.upperBetaLimit = Math.PI;
  44263. _this.lowerRadiusLimit = null;
  44264. _this.upperRadiusLimit = null;
  44265. _this.inertialPanningX = 0;
  44266. _this.inertialPanningY = 0;
  44267. _this.pinchToPanMaxDistance = 20;
  44268. _this.panningDistanceLimit = null;
  44269. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44270. _this.panningInertia = 0.9;
  44271. //-- end properties for backward compatibility for inputs
  44272. _this.zoomOnFactor = 1;
  44273. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44274. _this.allowUpsideDown = true;
  44275. _this._viewMatrix = new BABYLON.Matrix();
  44276. // Panning
  44277. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44278. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44279. _this.checkCollisions = false;
  44280. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44281. _this._previousPosition = BABYLON.Vector3.Zero();
  44282. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44283. _this._newPosition = BABYLON.Vector3.Zero();
  44284. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44285. if (collidedMesh === void 0) { collidedMesh = null; }
  44286. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44287. newPosition.multiplyInPlace(_this._collider._radius);
  44288. }
  44289. if (!collidedMesh) {
  44290. _this._previousPosition.copyFrom(_this.position);
  44291. }
  44292. else {
  44293. _this.setPosition(newPosition);
  44294. if (_this.onCollide) {
  44295. _this.onCollide(collidedMesh);
  44296. }
  44297. }
  44298. // Recompute because of constraints
  44299. var cosa = Math.cos(_this.alpha);
  44300. var sina = Math.sin(_this.alpha);
  44301. var cosb = Math.cos(_this.beta);
  44302. var sinb = Math.sin(_this.beta);
  44303. if (sinb === 0) {
  44304. sinb = 0.0001;
  44305. }
  44306. var target = _this._getTargetPosition();
  44307. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44308. _this.position.copyFrom(_this._newPosition);
  44309. var up = _this.upVector;
  44310. if (_this.allowUpsideDown && _this.beta < 0) {
  44311. up = up.clone();
  44312. up = up.negate();
  44313. }
  44314. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44315. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44316. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44317. _this._collisionTriggered = false;
  44318. };
  44319. _this._target = BABYLON.Vector3.Zero();
  44320. if (target) {
  44321. _this.setTarget(target);
  44322. }
  44323. _this.alpha = alpha;
  44324. _this.beta = beta;
  44325. _this.radius = radius;
  44326. _this.getViewMatrix();
  44327. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44328. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44329. return _this;
  44330. }
  44331. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44332. get: function () {
  44333. return this._target;
  44334. },
  44335. set: function (value) {
  44336. this.setTarget(value);
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44342. //-- begin properties for backward compatibility for inputs
  44343. get: function () {
  44344. var pointers = this.inputs.attached["pointers"];
  44345. if (pointers)
  44346. return pointers.angularSensibilityX;
  44347. return 0;
  44348. },
  44349. set: function (value) {
  44350. var pointers = this.inputs.attached["pointers"];
  44351. if (pointers) {
  44352. pointers.angularSensibilityX = value;
  44353. }
  44354. },
  44355. enumerable: true,
  44356. configurable: true
  44357. });
  44358. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44359. get: function () {
  44360. var pointers = this.inputs.attached["pointers"];
  44361. if (pointers)
  44362. return pointers.angularSensibilityY;
  44363. return 0;
  44364. },
  44365. set: function (value) {
  44366. var pointers = this.inputs.attached["pointers"];
  44367. if (pointers) {
  44368. pointers.angularSensibilityY = value;
  44369. }
  44370. },
  44371. enumerable: true,
  44372. configurable: true
  44373. });
  44374. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44375. get: function () {
  44376. var pointers = this.inputs.attached["pointers"];
  44377. if (pointers)
  44378. return pointers.pinchPrecision;
  44379. return 0;
  44380. },
  44381. set: function (value) {
  44382. var pointers = this.inputs.attached["pointers"];
  44383. if (pointers) {
  44384. pointers.pinchPrecision = value;
  44385. }
  44386. },
  44387. enumerable: true,
  44388. configurable: true
  44389. });
  44390. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44391. get: function () {
  44392. var pointers = this.inputs.attached["pointers"];
  44393. if (pointers)
  44394. return pointers.pinchDeltaPercentage;
  44395. return 0;
  44396. },
  44397. set: function (value) {
  44398. var pointers = this.inputs.attached["pointers"];
  44399. if (pointers) {
  44400. pointers.pinchDeltaPercentage = value;
  44401. }
  44402. },
  44403. enumerable: true,
  44404. configurable: true
  44405. });
  44406. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44407. get: function () {
  44408. var pointers = this.inputs.attached["pointers"];
  44409. if (pointers)
  44410. return pointers.panningSensibility;
  44411. return 0;
  44412. },
  44413. set: function (value) {
  44414. var pointers = this.inputs.attached["pointers"];
  44415. if (pointers) {
  44416. pointers.panningSensibility = value;
  44417. }
  44418. },
  44419. enumerable: true,
  44420. configurable: true
  44421. });
  44422. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44423. get: function () {
  44424. var keyboard = this.inputs.attached["keyboard"];
  44425. if (keyboard)
  44426. return keyboard.keysUp;
  44427. return [];
  44428. },
  44429. set: function (value) {
  44430. var keyboard = this.inputs.attached["keyboard"];
  44431. if (keyboard)
  44432. keyboard.keysUp = value;
  44433. },
  44434. enumerable: true,
  44435. configurable: true
  44436. });
  44437. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44438. get: function () {
  44439. var keyboard = this.inputs.attached["keyboard"];
  44440. if (keyboard)
  44441. return keyboard.keysDown;
  44442. return [];
  44443. },
  44444. set: function (value) {
  44445. var keyboard = this.inputs.attached["keyboard"];
  44446. if (keyboard)
  44447. keyboard.keysDown = value;
  44448. },
  44449. enumerable: true,
  44450. configurable: true
  44451. });
  44452. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44453. get: function () {
  44454. var keyboard = this.inputs.attached["keyboard"];
  44455. if (keyboard)
  44456. return keyboard.keysLeft;
  44457. return [];
  44458. },
  44459. set: function (value) {
  44460. var keyboard = this.inputs.attached["keyboard"];
  44461. if (keyboard)
  44462. keyboard.keysLeft = value;
  44463. },
  44464. enumerable: true,
  44465. configurable: true
  44466. });
  44467. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44468. get: function () {
  44469. var keyboard = this.inputs.attached["keyboard"];
  44470. if (keyboard)
  44471. return keyboard.keysRight;
  44472. return [];
  44473. },
  44474. set: function (value) {
  44475. var keyboard = this.inputs.attached["keyboard"];
  44476. if (keyboard)
  44477. keyboard.keysRight = value;
  44478. },
  44479. enumerable: true,
  44480. configurable: true
  44481. });
  44482. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44483. get: function () {
  44484. var mousewheel = this.inputs.attached["mousewheel"];
  44485. if (mousewheel)
  44486. return mousewheel.wheelPrecision;
  44487. return 0;
  44488. },
  44489. set: function (value) {
  44490. var mousewheel = this.inputs.attached["mousewheel"];
  44491. if (mousewheel)
  44492. mousewheel.wheelPrecision = value;
  44493. },
  44494. enumerable: true,
  44495. configurable: true
  44496. });
  44497. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44498. get: function () {
  44499. var mousewheel = this.inputs.attached["mousewheel"];
  44500. if (mousewheel)
  44501. return mousewheel.wheelDeltaPercentage;
  44502. return 0;
  44503. },
  44504. set: function (value) {
  44505. var mousewheel = this.inputs.attached["mousewheel"];
  44506. if (mousewheel)
  44507. mousewheel.wheelDeltaPercentage = value;
  44508. },
  44509. enumerable: true,
  44510. configurable: true
  44511. });
  44512. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44513. get: function () {
  44514. return this._bouncingBehavior;
  44515. },
  44516. enumerable: true,
  44517. configurable: true
  44518. });
  44519. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44520. get: function () {
  44521. return this._bouncingBehavior != null;
  44522. },
  44523. set: function (value) {
  44524. if (value === this.useBouncingBehavior) {
  44525. return;
  44526. }
  44527. if (value) {
  44528. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44529. this.addBehavior(this._bouncingBehavior);
  44530. }
  44531. else if (this._bouncingBehavior) {
  44532. this.removeBehavior(this._bouncingBehavior);
  44533. this._bouncingBehavior = null;
  44534. }
  44535. },
  44536. enumerable: true,
  44537. configurable: true
  44538. });
  44539. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44540. get: function () {
  44541. return this._framingBehavior;
  44542. },
  44543. enumerable: true,
  44544. configurable: true
  44545. });
  44546. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44547. get: function () {
  44548. return this._framingBehavior != null;
  44549. },
  44550. set: function (value) {
  44551. if (value === this.useFramingBehavior) {
  44552. return;
  44553. }
  44554. if (value) {
  44555. this._framingBehavior = new BABYLON.FramingBehavior();
  44556. this.addBehavior(this._framingBehavior);
  44557. }
  44558. else if (this._framingBehavior) {
  44559. this.removeBehavior(this._framingBehavior);
  44560. this._framingBehavior = null;
  44561. }
  44562. },
  44563. enumerable: true,
  44564. configurable: true
  44565. });
  44566. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44567. get: function () {
  44568. return this._autoRotationBehavior;
  44569. },
  44570. enumerable: true,
  44571. configurable: true
  44572. });
  44573. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44574. get: function () {
  44575. return this._autoRotationBehavior != null;
  44576. },
  44577. set: function (value) {
  44578. if (value === this.useAutoRotationBehavior) {
  44579. return;
  44580. }
  44581. if (value) {
  44582. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44583. this.addBehavior(this._autoRotationBehavior);
  44584. }
  44585. else if (this._autoRotationBehavior) {
  44586. this.removeBehavior(this._autoRotationBehavior);
  44587. this._autoRotationBehavior = null;
  44588. }
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. // Cache
  44594. ArcRotateCamera.prototype._initCache = function () {
  44595. _super.prototype._initCache.call(this);
  44596. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44597. this._cache.alpha = undefined;
  44598. this._cache.beta = undefined;
  44599. this._cache.radius = undefined;
  44600. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44601. };
  44602. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44603. if (!ignoreParentClass) {
  44604. _super.prototype._updateCache.call(this);
  44605. }
  44606. this._cache._target.copyFrom(this._getTargetPosition());
  44607. this._cache.alpha = this.alpha;
  44608. this._cache.beta = this.beta;
  44609. this._cache.radius = this.radius;
  44610. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44611. };
  44612. ArcRotateCamera.prototype._getTargetPosition = function () {
  44613. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44614. var pos = this._targetHost.getAbsolutePosition();
  44615. if (this._targetBoundingCenter) {
  44616. pos.addToRef(this._targetBoundingCenter, this._target);
  44617. }
  44618. else {
  44619. this._target.copyFrom(pos);
  44620. }
  44621. }
  44622. var lockedTargetPosition = this._getLockedTargetPosition();
  44623. if (lockedTargetPosition) {
  44624. return lockedTargetPosition;
  44625. }
  44626. return this._target;
  44627. };
  44628. ArcRotateCamera.prototype.storeState = function () {
  44629. this._storedAlpha = this.alpha;
  44630. this._storedBeta = this.beta;
  44631. this._storedRadius = this.radius;
  44632. this._storedTarget = this._getTargetPosition().clone();
  44633. return _super.prototype.storeState.call(this);
  44634. };
  44635. /**
  44636. * Restored camera state. You must call storeState() first
  44637. */
  44638. ArcRotateCamera.prototype._restoreStateValues = function () {
  44639. if (!_super.prototype._restoreStateValues.call(this)) {
  44640. return false;
  44641. }
  44642. this.alpha = this._storedAlpha;
  44643. this.beta = this._storedBeta;
  44644. this.radius = this._storedRadius;
  44645. this.setTarget(this._storedTarget.clone());
  44646. this.inertialAlphaOffset = 0;
  44647. this.inertialBetaOffset = 0;
  44648. this.inertialRadiusOffset = 0;
  44649. this.inertialPanningX = 0;
  44650. this.inertialPanningY = 0;
  44651. return true;
  44652. };
  44653. // Synchronized
  44654. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44655. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44656. return false;
  44657. return this._cache._target.equals(this._getTargetPosition())
  44658. && this._cache.alpha === this.alpha
  44659. && this._cache.beta === this.beta
  44660. && this._cache.radius === this.radius
  44661. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44662. };
  44663. // Methods
  44664. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44665. var _this = this;
  44666. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44667. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44668. this._useCtrlForPanning = useCtrlForPanning;
  44669. this._panningMouseButton = panningMouseButton;
  44670. this.inputs.attachElement(element, noPreventDefault);
  44671. this._reset = function () {
  44672. _this.inertialAlphaOffset = 0;
  44673. _this.inertialBetaOffset = 0;
  44674. _this.inertialRadiusOffset = 0;
  44675. _this.inertialPanningX = 0;
  44676. _this.inertialPanningY = 0;
  44677. };
  44678. };
  44679. ArcRotateCamera.prototype.detachControl = function (element) {
  44680. this.inputs.detachElement(element);
  44681. if (this._reset) {
  44682. this._reset();
  44683. }
  44684. };
  44685. ArcRotateCamera.prototype._checkInputs = function () {
  44686. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44687. if (this._collisionTriggered) {
  44688. return;
  44689. }
  44690. this.inputs.checkInputs();
  44691. // Inertia
  44692. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44693. if (this.getScene().useRightHandedSystem) {
  44694. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44695. }
  44696. else {
  44697. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44698. }
  44699. this.beta += this.inertialBetaOffset;
  44700. this.radius -= this.inertialRadiusOffset;
  44701. this.inertialAlphaOffset *= this.inertia;
  44702. this.inertialBetaOffset *= this.inertia;
  44703. this.inertialRadiusOffset *= this.inertia;
  44704. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44705. this.inertialAlphaOffset = 0;
  44706. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44707. this.inertialBetaOffset = 0;
  44708. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44709. this.inertialRadiusOffset = 0;
  44710. }
  44711. // Panning inertia
  44712. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44713. if (!this._localDirection) {
  44714. this._localDirection = BABYLON.Vector3.Zero();
  44715. this._transformedDirection = BABYLON.Vector3.Zero();
  44716. }
  44717. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44718. this._localDirection.multiplyInPlace(this.panningAxis);
  44719. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44720. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44721. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44722. if (!this.panningAxis.y) {
  44723. this._transformedDirection.y = 0;
  44724. }
  44725. if (!this._targetHost) {
  44726. if (this.panningDistanceLimit) {
  44727. this._transformedDirection.addInPlace(this._target);
  44728. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44729. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44730. this._target.copyFrom(this._transformedDirection);
  44731. }
  44732. }
  44733. else {
  44734. this._target.addInPlace(this._transformedDirection);
  44735. }
  44736. }
  44737. this.inertialPanningX *= this.panningInertia;
  44738. this.inertialPanningY *= this.panningInertia;
  44739. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44740. this.inertialPanningX = 0;
  44741. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44742. this.inertialPanningY = 0;
  44743. }
  44744. // Limits
  44745. this._checkLimits();
  44746. _super.prototype._checkInputs.call(this);
  44747. };
  44748. ArcRotateCamera.prototype._checkLimits = function () {
  44749. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44750. if (this.allowUpsideDown && this.beta > Math.PI) {
  44751. this.beta = this.beta - (2 * Math.PI);
  44752. }
  44753. }
  44754. else {
  44755. if (this.beta < this.lowerBetaLimit) {
  44756. this.beta = this.lowerBetaLimit;
  44757. }
  44758. }
  44759. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44760. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44761. this.beta = this.beta + (2 * Math.PI);
  44762. }
  44763. }
  44764. else {
  44765. if (this.beta > this.upperBetaLimit) {
  44766. this.beta = this.upperBetaLimit;
  44767. }
  44768. }
  44769. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44770. this.alpha = this.lowerAlphaLimit;
  44771. }
  44772. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44773. this.alpha = this.upperAlphaLimit;
  44774. }
  44775. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44776. this.radius = this.lowerRadiusLimit;
  44777. }
  44778. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44779. this.radius = this.upperRadiusLimit;
  44780. }
  44781. };
  44782. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44783. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44784. this.radius = radiusv3.length();
  44785. if (this.radius === 0) {
  44786. this.radius = 0.0001; // Just to avoid division by zero
  44787. }
  44788. // Alpha
  44789. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44790. if (radiusv3.z < 0) {
  44791. this.alpha = 2 * Math.PI - this.alpha;
  44792. }
  44793. // Beta
  44794. this.beta = Math.acos(radiusv3.y / this.radius);
  44795. this._checkLimits();
  44796. };
  44797. ArcRotateCamera.prototype.setPosition = function (position) {
  44798. if (this.position.equals(position)) {
  44799. return;
  44800. }
  44801. this.position.copyFrom(position);
  44802. this.rebuildAnglesAndRadius();
  44803. };
  44804. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44805. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44806. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44807. if (target.getBoundingInfo) {
  44808. if (toBoundingCenter) {
  44809. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44810. }
  44811. else {
  44812. this._targetBoundingCenter = null;
  44813. }
  44814. this._targetHost = target;
  44815. this._target = this._getTargetPosition();
  44816. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44817. }
  44818. else {
  44819. var newTarget = target;
  44820. var currentTarget = this._getTargetPosition();
  44821. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44822. return;
  44823. }
  44824. this._targetHost = null;
  44825. this._target = newTarget;
  44826. this._targetBoundingCenter = null;
  44827. this.onMeshTargetChangedObservable.notifyObservers(null);
  44828. }
  44829. this.rebuildAnglesAndRadius();
  44830. };
  44831. ArcRotateCamera.prototype._getViewMatrix = function () {
  44832. // Compute
  44833. var cosa = Math.cos(this.alpha);
  44834. var sina = Math.sin(this.alpha);
  44835. var cosb = Math.cos(this.beta);
  44836. var sinb = Math.sin(this.beta);
  44837. if (sinb === 0) {
  44838. sinb = 0.0001;
  44839. }
  44840. var target = this._getTargetPosition();
  44841. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44842. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44843. if (!this._collider) {
  44844. this._collider = new BABYLON.Collider();
  44845. }
  44846. this._collider._radius = this.collisionRadius;
  44847. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44848. this._collisionTriggered = true;
  44849. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44850. }
  44851. else {
  44852. this.position.copyFrom(this._newPosition);
  44853. var up = this.upVector;
  44854. if (this.allowUpsideDown && sinb < 0) {
  44855. up = up.clone();
  44856. up = up.negate();
  44857. }
  44858. if (this.getScene().useRightHandedSystem) {
  44859. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44860. }
  44861. else {
  44862. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44863. }
  44864. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44865. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44866. }
  44867. this._currentTarget = target;
  44868. return this._viewMatrix;
  44869. };
  44870. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44872. meshes = meshes || this.getScene().meshes;
  44873. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44874. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44875. this.radius = distance * this.zoomOnFactor;
  44876. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44877. };
  44878. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44879. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44880. var meshesOrMinMaxVector;
  44881. var distance;
  44882. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44883. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44884. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44885. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44886. }
  44887. else {
  44888. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44889. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44890. distance = minMaxVectorAndDistance.distance;
  44891. }
  44892. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44893. if (!doNotUpdateMaxZ) {
  44894. this.maxZ = distance * 2;
  44895. }
  44896. };
  44897. /**
  44898. * @override
  44899. * Override Camera.createRigCamera
  44900. */
  44901. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44902. var alphaShift = 0;
  44903. switch (this.cameraRigMode) {
  44904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44906. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44907. case BABYLON.Camera.RIG_MODE_VR:
  44908. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44909. break;
  44910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44911. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44912. break;
  44913. }
  44914. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44915. rigCam._cameraRigParams = {};
  44916. return rigCam;
  44917. };
  44918. /**
  44919. * @override
  44920. * Override Camera._updateRigCameras
  44921. */
  44922. ArcRotateCamera.prototype._updateRigCameras = function () {
  44923. var camLeft = this._rigCameras[0];
  44924. var camRight = this._rigCameras[1];
  44925. camLeft.beta = camRight.beta = this.beta;
  44926. camLeft.radius = camRight.radius = this.radius;
  44927. switch (this.cameraRigMode) {
  44928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44931. case BABYLON.Camera.RIG_MODE_VR:
  44932. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44933. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44934. break;
  44935. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44936. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44937. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44938. break;
  44939. }
  44940. _super.prototype._updateRigCameras.call(this);
  44941. };
  44942. ArcRotateCamera.prototype.dispose = function () {
  44943. this.inputs.clear();
  44944. _super.prototype.dispose.call(this);
  44945. };
  44946. ArcRotateCamera.prototype.getClassName = function () {
  44947. return "ArcRotateCamera";
  44948. };
  44949. __decorate([
  44950. BABYLON.serialize()
  44951. ], ArcRotateCamera.prototype, "alpha", void 0);
  44952. __decorate([
  44953. BABYLON.serialize()
  44954. ], ArcRotateCamera.prototype, "beta", void 0);
  44955. __decorate([
  44956. BABYLON.serialize()
  44957. ], ArcRotateCamera.prototype, "radius", void 0);
  44958. __decorate([
  44959. BABYLON.serializeAsVector3("target")
  44960. ], ArcRotateCamera.prototype, "_target", void 0);
  44961. __decorate([
  44962. BABYLON.serialize()
  44963. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44964. __decorate([
  44965. BABYLON.serialize()
  44966. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44967. __decorate([
  44968. BABYLON.serialize()
  44969. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44970. __decorate([
  44971. BABYLON.serialize()
  44972. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44973. __decorate([
  44974. BABYLON.serialize()
  44975. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44976. __decorate([
  44977. BABYLON.serialize()
  44978. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44979. __decorate([
  44980. BABYLON.serialize()
  44981. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44982. __decorate([
  44983. BABYLON.serialize()
  44984. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44985. __decorate([
  44986. BABYLON.serialize()
  44987. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44988. __decorate([
  44989. BABYLON.serialize()
  44990. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44991. __decorate([
  44992. BABYLON.serialize()
  44993. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44994. __decorate([
  44995. BABYLON.serialize()
  44996. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44997. __decorate([
  44998. BABYLON.serialize()
  44999. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45000. __decorate([
  45001. BABYLON.serializeAsVector3()
  45002. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45003. __decorate([
  45004. BABYLON.serialize()
  45005. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45006. __decorate([
  45007. BABYLON.serialize()
  45008. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45009. __decorate([
  45010. BABYLON.serialize()
  45011. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45012. return ArcRotateCamera;
  45013. }(BABYLON.TargetCamera));
  45014. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45015. })(BABYLON || (BABYLON = {}));
  45016. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45017. var BABYLON;
  45018. (function (BABYLON) {
  45019. /**
  45020. * The HemisphericLight simulates the ambient environment light,
  45021. * so the passed direction is the light reflection direction, not the incoming direction.
  45022. */
  45023. var HemisphericLight = /** @class */ (function (_super) {
  45024. __extends(HemisphericLight, _super);
  45025. /**
  45026. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45027. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45028. * The HemisphericLight can't cast shadows.
  45029. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45030. * @param name The friendly name of the light
  45031. * @param direction The direction of the light reflection
  45032. * @param scene The scene the light belongs to
  45033. */
  45034. function HemisphericLight(name, direction, scene) {
  45035. var _this = _super.call(this, name, scene) || this;
  45036. /**
  45037. * The groundColor is the light in the opposite direction to the one specified during creation.
  45038. * 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.
  45039. */
  45040. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45041. _this.direction = direction || BABYLON.Vector3.Up();
  45042. return _this;
  45043. }
  45044. HemisphericLight.prototype._buildUniformLayout = function () {
  45045. this._uniformBuffer.addUniform("vLightData", 4);
  45046. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45047. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45048. this._uniformBuffer.addUniform("vLightGround", 3);
  45049. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45050. this._uniformBuffer.addUniform("depthValues", 2);
  45051. this._uniformBuffer.create();
  45052. };
  45053. /**
  45054. * Returns the string "HemisphericLight".
  45055. * @return The class name
  45056. */
  45057. HemisphericLight.prototype.getClassName = function () {
  45058. return "HemisphericLight";
  45059. };
  45060. /**
  45061. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45062. * Returns the updated direction.
  45063. * @param target The target the direction should point to
  45064. * @return The computed direction
  45065. */
  45066. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45067. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45068. return this.direction;
  45069. };
  45070. /**
  45071. * Returns the shadow generator associated to the light.
  45072. * @returns Always null for hemispheric lights because it does not support shadows.
  45073. */
  45074. HemisphericLight.prototype.getShadowGenerator = function () {
  45075. return null;
  45076. };
  45077. /**
  45078. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45079. * @param effect The effect to update
  45080. * @param lightIndex The index of the light in the effect to update
  45081. * @returns The hemispheric light
  45082. */
  45083. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45084. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45085. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45086. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45087. return this;
  45088. };
  45089. /**
  45090. * @ignore internal use only.
  45091. */
  45092. HemisphericLight.prototype._getWorldMatrix = function () {
  45093. if (!this._worldMatrix) {
  45094. this._worldMatrix = BABYLON.Matrix.Identity();
  45095. }
  45096. return this._worldMatrix;
  45097. };
  45098. /**
  45099. * Returns the integer 3.
  45100. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45101. */
  45102. HemisphericLight.prototype.getTypeID = function () {
  45103. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45104. };
  45105. __decorate([
  45106. BABYLON.serializeAsColor3()
  45107. ], HemisphericLight.prototype, "groundColor", void 0);
  45108. __decorate([
  45109. BABYLON.serializeAsVector3()
  45110. ], HemisphericLight.prototype, "direction", void 0);
  45111. return HemisphericLight;
  45112. }(BABYLON.Light));
  45113. BABYLON.HemisphericLight = HemisphericLight;
  45114. })(BABYLON || (BABYLON = {}));
  45115. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45116. var BABYLON;
  45117. (function (BABYLON) {
  45118. /**
  45119. * Base implementation of @see IShadowLight
  45120. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45121. */
  45122. var ShadowLight = /** @class */ (function (_super) {
  45123. __extends(ShadowLight, _super);
  45124. function ShadowLight() {
  45125. var _this = _super !== null && _super.apply(this, arguments) || this;
  45126. _this._needProjectionMatrixCompute = true;
  45127. return _this;
  45128. }
  45129. ShadowLight.prototype._setPosition = function (value) {
  45130. this._position = value;
  45131. };
  45132. Object.defineProperty(ShadowLight.prototype, "position", {
  45133. /**
  45134. * Sets the position the shadow will be casted from. Also use as the light position for both
  45135. * point and spot lights.
  45136. */
  45137. get: function () {
  45138. return this._position;
  45139. },
  45140. /**
  45141. * Sets the position the shadow will be casted from. Also use as the light position for both
  45142. * point and spot lights.
  45143. */
  45144. set: function (value) {
  45145. this._setPosition(value);
  45146. },
  45147. enumerable: true,
  45148. configurable: true
  45149. });
  45150. ShadowLight.prototype._setDirection = function (value) {
  45151. this._direction = value;
  45152. };
  45153. Object.defineProperty(ShadowLight.prototype, "direction", {
  45154. /**
  45155. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45156. * Also use as the light direction on spot and directional lights.
  45157. */
  45158. get: function () {
  45159. return this._direction;
  45160. },
  45161. /**
  45162. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45163. * Also use as the light direction on spot and directional lights.
  45164. */
  45165. set: function (value) {
  45166. this._setDirection(value);
  45167. },
  45168. enumerable: true,
  45169. configurable: true
  45170. });
  45171. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45172. /**
  45173. * Gets the shadow projection clipping minimum z value.
  45174. */
  45175. get: function () {
  45176. return this._shadowMinZ;
  45177. },
  45178. /**
  45179. * Sets the shadow projection clipping minimum z value.
  45180. */
  45181. set: function (value) {
  45182. this._shadowMinZ = value;
  45183. this.forceProjectionMatrixCompute();
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45189. /**
  45190. * Sets the shadow projection clipping maximum z value.
  45191. */
  45192. get: function () {
  45193. return this._shadowMaxZ;
  45194. },
  45195. /**
  45196. * Gets the shadow projection clipping maximum z value.
  45197. */
  45198. set: function (value) {
  45199. this._shadowMaxZ = value;
  45200. this.forceProjectionMatrixCompute();
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. /**
  45206. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45207. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45208. */
  45209. ShadowLight.prototype.computeTransformedInformation = function () {
  45210. if (this.parent && this.parent.getWorldMatrix) {
  45211. if (!this.transformedPosition) {
  45212. this.transformedPosition = BABYLON.Vector3.Zero();
  45213. }
  45214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45215. // In case the direction is present.
  45216. if (this.direction) {
  45217. if (!this.transformedDirection) {
  45218. this.transformedDirection = BABYLON.Vector3.Zero();
  45219. }
  45220. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45221. }
  45222. return true;
  45223. }
  45224. return false;
  45225. };
  45226. /**
  45227. * Return the depth scale used for the shadow map.
  45228. * @returns the depth scale.
  45229. */
  45230. ShadowLight.prototype.getDepthScale = function () {
  45231. return 50.0;
  45232. };
  45233. /**
  45234. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45235. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45236. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45237. */
  45238. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45239. return this.transformedDirection ? this.transformedDirection : this.direction;
  45240. };
  45241. /**
  45242. * Returns the ShadowLight absolute position in the World.
  45243. * @returns the position vector in world space
  45244. */
  45245. ShadowLight.prototype.getAbsolutePosition = function () {
  45246. return this.transformedPosition ? this.transformedPosition : this.position;
  45247. };
  45248. /**
  45249. * Sets the ShadowLight direction toward the passed target.
  45250. * @param target The point tot target in local space
  45251. * @returns the updated ShadowLight direction
  45252. */
  45253. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45254. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45255. return this.direction;
  45256. };
  45257. /**
  45258. * Returns the light rotation in euler definition.
  45259. * @returns the x y z rotation in local space.
  45260. */
  45261. ShadowLight.prototype.getRotation = function () {
  45262. this.direction.normalize();
  45263. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45264. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45265. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45266. };
  45267. /**
  45268. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45269. * @returns true if a cube texture needs to be use
  45270. */
  45271. ShadowLight.prototype.needCube = function () {
  45272. return false;
  45273. };
  45274. /**
  45275. * Detects if the projection matrix requires to be recomputed this frame.
  45276. * @returns true if it requires to be recomputed otherwise, false.
  45277. */
  45278. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45279. return this._needProjectionMatrixCompute;
  45280. };
  45281. /**
  45282. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45283. */
  45284. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45285. this._needProjectionMatrixCompute = true;
  45286. };
  45287. /**
  45288. * Get the world matrix of the sahdow lights.
  45289. * @ignore Internal Use Only
  45290. */
  45291. ShadowLight.prototype._getWorldMatrix = function () {
  45292. if (!this._worldMatrix) {
  45293. this._worldMatrix = BABYLON.Matrix.Identity();
  45294. }
  45295. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45296. return this._worldMatrix;
  45297. };
  45298. /**
  45299. * Gets the minZ used for shadow according to both the scene and the light.
  45300. * @param activeCamera The camera we are returning the min for
  45301. * @returns the depth min z
  45302. */
  45303. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45304. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45305. };
  45306. /**
  45307. * Gets the maxZ used for shadow according to both the scene and the light.
  45308. * @param activeCamera The camera we are returning the max for
  45309. * @returns the depth max z
  45310. */
  45311. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45312. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45313. };
  45314. /**
  45315. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45316. * @param matrix The materix to updated with the projection information
  45317. * @param viewMatrix The transform matrix of the light
  45318. * @param renderList The list of mesh to render in the map
  45319. * @returns The current light
  45320. */
  45321. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45322. if (this.customProjectionMatrixBuilder) {
  45323. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45324. }
  45325. else {
  45326. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45327. }
  45328. return this;
  45329. };
  45330. __decorate([
  45331. BABYLON.serializeAsVector3()
  45332. ], ShadowLight.prototype, "position", null);
  45333. __decorate([
  45334. BABYLON.serializeAsVector3()
  45335. ], ShadowLight.prototype, "direction", null);
  45336. __decorate([
  45337. BABYLON.serialize()
  45338. ], ShadowLight.prototype, "shadowMinZ", null);
  45339. __decorate([
  45340. BABYLON.serialize()
  45341. ], ShadowLight.prototype, "shadowMaxZ", null);
  45342. return ShadowLight;
  45343. }(BABYLON.Light));
  45344. BABYLON.ShadowLight = ShadowLight;
  45345. })(BABYLON || (BABYLON = {}));
  45346. //# sourceMappingURL=babylon.shadowLight.js.map
  45347. var BABYLON;
  45348. (function (BABYLON) {
  45349. /**
  45350. * A point light is a light defined by an unique point in world space.
  45351. * The light is emitted in every direction from this point.
  45352. * A good example of a point light is a standard light bulb.
  45353. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45354. */
  45355. var PointLight = /** @class */ (function (_super) {
  45356. __extends(PointLight, _super);
  45357. /**
  45358. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45359. * A PointLight emits the light in every direction.
  45360. * It can cast shadows.
  45361. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45362. * ```javascript
  45363. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45364. * ```
  45365. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45366. * @param name The light friendly name
  45367. * @param position The position of the point light in the scene
  45368. * @param scene The scene the lights belongs to
  45369. */
  45370. function PointLight(name, position, scene) {
  45371. var _this = _super.call(this, name, scene) || this;
  45372. _this._shadowAngle = Math.PI / 2;
  45373. _this.position = position;
  45374. return _this;
  45375. }
  45376. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45377. /**
  45378. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45379. * This specifies what angle the shadow will use to be created.
  45380. *
  45381. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45382. */
  45383. get: function () {
  45384. return this._shadowAngle;
  45385. },
  45386. /**
  45387. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45388. * This specifies what angle the shadow will use to be created.
  45389. *
  45390. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45391. */
  45392. set: function (value) {
  45393. this._shadowAngle = value;
  45394. this.forceProjectionMatrixCompute();
  45395. },
  45396. enumerable: true,
  45397. configurable: true
  45398. });
  45399. Object.defineProperty(PointLight.prototype, "direction", {
  45400. /**
  45401. * Gets the direction if it has been set.
  45402. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45403. */
  45404. get: function () {
  45405. return this._direction;
  45406. },
  45407. /**
  45408. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45409. */
  45410. set: function (value) {
  45411. var previousNeedCube = this.needCube();
  45412. this._direction = value;
  45413. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45414. this._shadowGenerator.recreateShadowMap();
  45415. }
  45416. },
  45417. enumerable: true,
  45418. configurable: true
  45419. });
  45420. /**
  45421. * Returns the string "PointLight"
  45422. * @returns the class name
  45423. */
  45424. PointLight.prototype.getClassName = function () {
  45425. return "PointLight";
  45426. };
  45427. /**
  45428. * Returns the integer 0.
  45429. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45430. */
  45431. PointLight.prototype.getTypeID = function () {
  45432. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45433. };
  45434. /**
  45435. * Specifies wether or not the shadowmap should be a cube texture.
  45436. * @returns true if the shadowmap needs to be a cube texture.
  45437. */
  45438. PointLight.prototype.needCube = function () {
  45439. return !this.direction;
  45440. };
  45441. /**
  45442. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45443. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45444. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45445. */
  45446. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45447. if (this.direction) {
  45448. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45449. }
  45450. else {
  45451. switch (faceIndex) {
  45452. case 0:
  45453. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45454. case 1:
  45455. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45456. case 2:
  45457. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45458. case 3:
  45459. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45460. case 4:
  45461. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45462. case 5:
  45463. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45464. }
  45465. }
  45466. return BABYLON.Vector3.Zero();
  45467. };
  45468. /**
  45469. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45470. * - fov = PI / 2
  45471. * - aspect ratio : 1.0
  45472. * - z-near and far equal to the active camera minZ and maxZ.
  45473. * Returns the PointLight.
  45474. */
  45475. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45476. var activeCamera = this.getScene().activeCamera;
  45477. if (!activeCamera) {
  45478. return;
  45479. }
  45480. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45481. };
  45482. PointLight.prototype._buildUniformLayout = function () {
  45483. this._uniformBuffer.addUniform("vLightData", 4);
  45484. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45485. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45486. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45487. this._uniformBuffer.addUniform("depthValues", 2);
  45488. this._uniformBuffer.create();
  45489. };
  45490. /**
  45491. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45492. * @param effect The effect to update
  45493. * @param lightIndex The index of the light in the effect to update
  45494. * @returns The point light
  45495. */
  45496. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45497. if (this.computeTransformedInformation()) {
  45498. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45499. return this;
  45500. }
  45501. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45502. return this;
  45503. };
  45504. __decorate([
  45505. BABYLON.serialize()
  45506. ], PointLight.prototype, "shadowAngle", null);
  45507. return PointLight;
  45508. }(BABYLON.ShadowLight));
  45509. BABYLON.PointLight = PointLight;
  45510. })(BABYLON || (BABYLON = {}));
  45511. //# sourceMappingURL=babylon.pointLight.js.map
  45512. var BABYLON;
  45513. (function (BABYLON) {
  45514. /**
  45515. * A directional light is defined by a direction (what a surprise!).
  45516. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45517. * 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.
  45518. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45519. */
  45520. var DirectionalLight = /** @class */ (function (_super) {
  45521. __extends(DirectionalLight, _super);
  45522. /**
  45523. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45524. * The directional light is emitted from everywhere in the given direction.
  45525. * It can cast shawdows.
  45526. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45527. * @param name The friendly name of the light
  45528. * @param direction The direction of the light
  45529. * @param scene The scene the light belongs to
  45530. */
  45531. function DirectionalLight(name, direction, scene) {
  45532. var _this = _super.call(this, name, scene) || this;
  45533. _this._shadowFrustumSize = 0;
  45534. _this._shadowOrthoScale = 0.5;
  45535. /**
  45536. * Automatically compute the projection matrix to best fit (including all the casters)
  45537. * on each frame.
  45538. */
  45539. _this.autoUpdateExtends = true;
  45540. // Cache
  45541. _this._orthoLeft = Number.MAX_VALUE;
  45542. _this._orthoRight = Number.MIN_VALUE;
  45543. _this._orthoTop = Number.MIN_VALUE;
  45544. _this._orthoBottom = Number.MAX_VALUE;
  45545. _this.position = direction.scale(-1.0);
  45546. _this.direction = direction;
  45547. return _this;
  45548. }
  45549. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45550. /**
  45551. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45552. */
  45553. get: function () {
  45554. return this._shadowFrustumSize;
  45555. },
  45556. /**
  45557. * Specifies a fix frustum size for the shadow generation.
  45558. */
  45559. set: function (value) {
  45560. this._shadowFrustumSize = value;
  45561. this.forceProjectionMatrixCompute();
  45562. },
  45563. enumerable: true,
  45564. configurable: true
  45565. });
  45566. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45567. /**
  45568. * Gets the shadow projection scale against the optimal computed one.
  45569. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45570. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45571. */
  45572. get: function () {
  45573. return this._shadowOrthoScale;
  45574. },
  45575. /**
  45576. * Sets the shadow projection scale against the optimal computed one.
  45577. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45578. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45579. */
  45580. set: function (value) {
  45581. this._shadowOrthoScale = value;
  45582. this.forceProjectionMatrixCompute();
  45583. },
  45584. enumerable: true,
  45585. configurable: true
  45586. });
  45587. /**
  45588. * Returns the string "DirectionalLight".
  45589. * @return The class name
  45590. */
  45591. DirectionalLight.prototype.getClassName = function () {
  45592. return "DirectionalLight";
  45593. };
  45594. /**
  45595. * Returns the integer 1.
  45596. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45597. */
  45598. DirectionalLight.prototype.getTypeID = function () {
  45599. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45600. };
  45601. /**
  45602. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45603. * Returns the DirectionalLight Shadow projection matrix.
  45604. */
  45605. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45606. if (this.shadowFrustumSize > 0) {
  45607. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45608. }
  45609. else {
  45610. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45611. }
  45612. };
  45613. /**
  45614. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45615. * Returns the DirectionalLight Shadow projection matrix.
  45616. */
  45617. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45618. var activeCamera = this.getScene().activeCamera;
  45619. if (!activeCamera) {
  45620. return;
  45621. }
  45622. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45623. };
  45624. /**
  45625. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45626. * Returns the DirectionalLight Shadow projection matrix.
  45627. */
  45628. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45629. var activeCamera = this.getScene().activeCamera;
  45630. if (!activeCamera) {
  45631. return;
  45632. }
  45633. // Check extends
  45634. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45635. var tempVector3 = BABYLON.Vector3.Zero();
  45636. this._orthoLeft = Number.MAX_VALUE;
  45637. this._orthoRight = Number.MIN_VALUE;
  45638. this._orthoTop = Number.MIN_VALUE;
  45639. this._orthoBottom = Number.MAX_VALUE;
  45640. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45641. var mesh = renderList[meshIndex];
  45642. if (!mesh) {
  45643. continue;
  45644. }
  45645. var boundingInfo = mesh.getBoundingInfo();
  45646. var boundingBox = boundingInfo.boundingBox;
  45647. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45648. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45649. if (tempVector3.x < this._orthoLeft)
  45650. this._orthoLeft = tempVector3.x;
  45651. if (tempVector3.y < this._orthoBottom)
  45652. this._orthoBottom = tempVector3.y;
  45653. if (tempVector3.x > this._orthoRight)
  45654. this._orthoRight = tempVector3.x;
  45655. if (tempVector3.y > this._orthoTop)
  45656. this._orthoTop = tempVector3.y;
  45657. }
  45658. }
  45659. }
  45660. var xOffset = this._orthoRight - this._orthoLeft;
  45661. var yOffset = this._orthoTop - this._orthoBottom;
  45662. 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);
  45663. };
  45664. DirectionalLight.prototype._buildUniformLayout = function () {
  45665. this._uniformBuffer.addUniform("vLightData", 4);
  45666. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45667. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45668. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45669. this._uniformBuffer.addUniform("depthValues", 2);
  45670. this._uniformBuffer.create();
  45671. };
  45672. /**
  45673. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45674. * @param effect The effect to update
  45675. * @param lightIndex The index of the light in the effect to update
  45676. * @returns The directional light
  45677. */
  45678. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45679. if (this.computeTransformedInformation()) {
  45680. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45681. return this;
  45682. }
  45683. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45684. return this;
  45685. };
  45686. /**
  45687. * Gets the minZ used for shadow according to both the scene and the light.
  45688. *
  45689. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45690. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45691. * @param activeCamera The camera we are returning the min for
  45692. * @returns the depth min z
  45693. */
  45694. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45695. return 1;
  45696. };
  45697. /**
  45698. * Gets the maxZ used for shadow according to both the scene and the light.
  45699. *
  45700. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45701. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45702. * @param activeCamera The camera we are returning the max for
  45703. * @returns the depth max z
  45704. */
  45705. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45706. return 1;
  45707. };
  45708. __decorate([
  45709. BABYLON.serialize()
  45710. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45711. __decorate([
  45712. BABYLON.serialize()
  45713. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45714. __decorate([
  45715. BABYLON.serialize()
  45716. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45717. return DirectionalLight;
  45718. }(BABYLON.ShadowLight));
  45719. BABYLON.DirectionalLight = DirectionalLight;
  45720. })(BABYLON || (BABYLON = {}));
  45721. //# sourceMappingURL=babylon.directionalLight.js.map
  45722. var BABYLON;
  45723. (function (BABYLON) {
  45724. /**
  45725. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45726. * These values define a cone of light starting from the position, emitting toward the direction.
  45727. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45728. * and the exponent defines the speed of the decay of the light with distance (reach).
  45729. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45730. */
  45731. var SpotLight = /** @class */ (function (_super) {
  45732. __extends(SpotLight, _super);
  45733. /**
  45734. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45735. * It can cast shadows.
  45736. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45737. * @param name The light friendly name
  45738. * @param position The position of the spot light in the scene
  45739. * @param direction The direction of the light in the scene
  45740. * @param angle The cone angle of the light in Radians
  45741. * @param exponent The light decay speed with the distance from the emission spot
  45742. * @param scene The scene the lights belongs to
  45743. */
  45744. function SpotLight(name, position, direction, angle, exponent, scene) {
  45745. var _this = _super.call(this, name, scene) || this;
  45746. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45747. _this._projectionTextureLightNear = 1e-6;
  45748. _this._projectionTextureLightFar = 1000.0;
  45749. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45750. _this._projectionTextureViewLightDirty = true;
  45751. _this._projectionTextureProjectionLightDirty = true;
  45752. _this._projectionTextureDirty = true;
  45753. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45754. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45755. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45756. _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);
  45757. _this.position = position;
  45758. _this.direction = direction;
  45759. _this.angle = angle;
  45760. _this.exponent = exponent;
  45761. return _this;
  45762. }
  45763. Object.defineProperty(SpotLight.prototype, "angle", {
  45764. /**
  45765. * Gets the cone angle of the spot light in Radians.
  45766. */
  45767. get: function () {
  45768. return this._angle;
  45769. },
  45770. /**
  45771. * Sets the cone angle of the spot light in Radians.
  45772. */
  45773. set: function (value) {
  45774. this._angle = value;
  45775. this._projectionTextureProjectionLightDirty = true;
  45776. this.forceProjectionMatrixCompute();
  45777. },
  45778. enumerable: true,
  45779. configurable: true
  45780. });
  45781. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45782. /**
  45783. * Allows scaling the angle of the light for shadow generation only.
  45784. */
  45785. get: function () {
  45786. return this._shadowAngleScale;
  45787. },
  45788. /**
  45789. * Allows scaling the angle of the light for shadow generation only.
  45790. */
  45791. set: function (value) {
  45792. this._shadowAngleScale = value;
  45793. this.forceProjectionMatrixCompute();
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45799. /**
  45800. * Allows reading the projecton texture
  45801. */
  45802. get: function () {
  45803. return this._projectionTextureMatrix;
  45804. },
  45805. enumerable: true,
  45806. configurable: true
  45807. });
  45808. ;
  45809. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45810. /**
  45811. * Gets the near clip of the Spotlight for texture projection.
  45812. */
  45813. get: function () {
  45814. return this._projectionTextureLightNear;
  45815. },
  45816. /**
  45817. * Sets the near clip of the Spotlight for texture projection.
  45818. */
  45819. set: function (value) {
  45820. this._projectionTextureLightNear = value;
  45821. this._projectionTextureProjectionLightDirty = true;
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45827. /**
  45828. * Gets the far clip of the Spotlight for texture projection.
  45829. */
  45830. get: function () {
  45831. return this._projectionTextureLightFar;
  45832. },
  45833. /**
  45834. * Sets the far clip of the Spotlight for texture projection.
  45835. */
  45836. set: function (value) {
  45837. this._projectionTextureLightFar = value;
  45838. this._projectionTextureProjectionLightDirty = true;
  45839. },
  45840. enumerable: true,
  45841. configurable: true
  45842. });
  45843. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45844. /**
  45845. * Gets the Up vector of the Spotlight for texture projection.
  45846. */
  45847. get: function () {
  45848. return this._projectionTextureUpDirection;
  45849. },
  45850. /**
  45851. * Sets the Up vector of the Spotlight for texture projection.
  45852. */
  45853. set: function (value) {
  45854. this._projectionTextureUpDirection = value;
  45855. this._projectionTextureProjectionLightDirty = true;
  45856. },
  45857. enumerable: true,
  45858. configurable: true
  45859. });
  45860. ;
  45861. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45862. /**
  45863. * Gets the projection texture of the light.
  45864. */
  45865. get: function () {
  45866. return this._projectionTexture;
  45867. },
  45868. /**
  45869. * Sets the projection texture of the light.
  45870. */
  45871. set: function (value) {
  45872. this._projectionTexture = value;
  45873. this._projectionTextureDirty = true;
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. /**
  45879. * Returns the string "SpotLight".
  45880. * @returns the class name
  45881. */
  45882. SpotLight.prototype.getClassName = function () {
  45883. return "SpotLight";
  45884. };
  45885. /**
  45886. * Returns the integer 2.
  45887. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45888. */
  45889. SpotLight.prototype.getTypeID = function () {
  45890. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45891. };
  45892. /**
  45893. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45894. */
  45895. SpotLight.prototype._setDirection = function (value) {
  45896. _super.prototype._setDirection.call(this, value);
  45897. this._projectionTextureViewLightDirty = true;
  45898. };
  45899. /**
  45900. * Overrides the position setter to recompute the projection texture view light Matrix.
  45901. */
  45902. SpotLight.prototype._setPosition = function (value) {
  45903. _super.prototype._setPosition.call(this, value);
  45904. this._projectionTextureViewLightDirty = true;
  45905. };
  45906. /**
  45907. * 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.
  45908. * Returns the SpotLight.
  45909. */
  45910. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45911. var activeCamera = this.getScene().activeCamera;
  45912. if (!activeCamera) {
  45913. return;
  45914. }
  45915. this._shadowAngleScale = this._shadowAngleScale || 1;
  45916. var angle = this._shadowAngleScale * this._angle;
  45917. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45918. };
  45919. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45920. this._projectionTextureViewLightDirty = false;
  45921. this._projectionTextureDirty = true;
  45922. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45923. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45924. };
  45925. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45926. this._projectionTextureProjectionLightDirty = false;
  45927. this._projectionTextureDirty = true;
  45928. var light_far = this.projectionTextureLightFar;
  45929. var light_near = this.projectionTextureLightNear;
  45930. var P = light_far / (light_far - light_near);
  45931. var Q = -P * light_near;
  45932. var S = 1.0 / Math.tan(this._angle / 2.0);
  45933. var A = 1.0;
  45934. 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);
  45935. };
  45936. /**
  45937. * Main function for light texture projection matrix computing.
  45938. */
  45939. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45940. this._projectionTextureDirty = false;
  45941. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45942. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45943. };
  45944. SpotLight.prototype._buildUniformLayout = function () {
  45945. this._uniformBuffer.addUniform("vLightData", 4);
  45946. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45947. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45948. this._uniformBuffer.addUniform("vLightDirection", 3);
  45949. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45950. this._uniformBuffer.addUniform("depthValues", 2);
  45951. this._uniformBuffer.create();
  45952. };
  45953. /**
  45954. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45955. * @param effect The effect to update
  45956. * @param lightIndex The index of the light in the effect to update
  45957. * @returns The spot light
  45958. */
  45959. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45960. var normalizeDirection;
  45961. if (this.computeTransformedInformation()) {
  45962. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45963. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45964. }
  45965. else {
  45966. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45967. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45968. }
  45969. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45970. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45971. if (this._projectionTextureViewLightDirty) {
  45972. this._computeProjectionTextureViewLightMatrix();
  45973. }
  45974. if (this._projectionTextureProjectionLightDirty) {
  45975. this._computeProjectionTextureProjectionLightMatrix();
  45976. }
  45977. if (this._projectionTextureDirty) {
  45978. this._computeProjectionTextureMatrix();
  45979. }
  45980. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45981. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45982. }
  45983. return this;
  45984. };
  45985. /**
  45986. * Disposes the light and the associated resources.
  45987. */
  45988. SpotLight.prototype.dispose = function () {
  45989. _super.prototype.dispose.call(this);
  45990. if (this._projectionTexture) {
  45991. this._projectionTexture.dispose();
  45992. }
  45993. };
  45994. __decorate([
  45995. BABYLON.serialize()
  45996. ], SpotLight.prototype, "angle", null);
  45997. __decorate([
  45998. BABYLON.serialize()
  45999. ], SpotLight.prototype, "shadowAngleScale", null);
  46000. __decorate([
  46001. BABYLON.serialize()
  46002. ], SpotLight.prototype, "exponent", void 0);
  46003. __decorate([
  46004. BABYLON.serialize()
  46005. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46006. __decorate([
  46007. BABYLON.serialize()
  46008. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46009. __decorate([
  46010. BABYLON.serialize()
  46011. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46012. __decorate([
  46013. BABYLON.serializeAsTexture("projectedLightTexture")
  46014. ], SpotLight.prototype, "_projectionTexture", void 0);
  46015. return SpotLight;
  46016. }(BABYLON.ShadowLight));
  46017. BABYLON.SpotLight = SpotLight;
  46018. })(BABYLON || (BABYLON = {}));
  46019. //# sourceMappingURL=babylon.spotLight.js.map
  46020. var BABYLON;
  46021. (function (BABYLON) {
  46022. var AnimationRange = /** @class */ (function () {
  46023. function AnimationRange(name, from, to) {
  46024. this.name = name;
  46025. this.from = from;
  46026. this.to = to;
  46027. }
  46028. AnimationRange.prototype.clone = function () {
  46029. return new AnimationRange(this.name, this.from, this.to);
  46030. };
  46031. return AnimationRange;
  46032. }());
  46033. BABYLON.AnimationRange = AnimationRange;
  46034. /**
  46035. * Composed of a frame, and an action function
  46036. */
  46037. var AnimationEvent = /** @class */ (function () {
  46038. function AnimationEvent(frame, action, onlyOnce) {
  46039. this.frame = frame;
  46040. this.action = action;
  46041. this.onlyOnce = onlyOnce;
  46042. this.isDone = false;
  46043. }
  46044. return AnimationEvent;
  46045. }());
  46046. BABYLON.AnimationEvent = AnimationEvent;
  46047. var PathCursor = /** @class */ (function () {
  46048. function PathCursor(path) {
  46049. this.path = path;
  46050. this._onchange = new Array();
  46051. this.value = 0;
  46052. this.animations = new Array();
  46053. }
  46054. PathCursor.prototype.getPoint = function () {
  46055. var point = this.path.getPointAtLengthPosition(this.value);
  46056. return new BABYLON.Vector3(point.x, 0, point.y);
  46057. };
  46058. PathCursor.prototype.moveAhead = function (step) {
  46059. if (step === void 0) { step = 0.002; }
  46060. this.move(step);
  46061. return this;
  46062. };
  46063. PathCursor.prototype.moveBack = function (step) {
  46064. if (step === void 0) { step = 0.002; }
  46065. this.move(-step);
  46066. return this;
  46067. };
  46068. PathCursor.prototype.move = function (step) {
  46069. if (Math.abs(step) > 1) {
  46070. throw "step size should be less than 1.";
  46071. }
  46072. this.value += step;
  46073. this.ensureLimits();
  46074. this.raiseOnChange();
  46075. return this;
  46076. };
  46077. PathCursor.prototype.ensureLimits = function () {
  46078. while (this.value > 1) {
  46079. this.value -= 1;
  46080. }
  46081. while (this.value < 0) {
  46082. this.value += 1;
  46083. }
  46084. return this;
  46085. };
  46086. // used by animation engine
  46087. PathCursor.prototype.raiseOnChange = function () {
  46088. var _this = this;
  46089. this._onchange.forEach(function (f) { return f(_this); });
  46090. return this;
  46091. };
  46092. PathCursor.prototype.onchange = function (f) {
  46093. this._onchange.push(f);
  46094. return this;
  46095. };
  46096. return PathCursor;
  46097. }());
  46098. BABYLON.PathCursor = PathCursor;
  46099. var AnimationKeyInterpolation;
  46100. (function (AnimationKeyInterpolation) {
  46101. /**
  46102. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46103. */
  46104. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46105. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46106. var Animation = /** @class */ (function () {
  46107. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46108. this.name = name;
  46109. this.targetProperty = targetProperty;
  46110. this.framePerSecond = framePerSecond;
  46111. this.dataType = dataType;
  46112. this.loopMode = loopMode;
  46113. this.enableBlending = enableBlending;
  46114. this._runtimeAnimations = new Array();
  46115. // The set of event that will be linked to this animation
  46116. this._events = new Array();
  46117. this.blendingSpeed = 0.01;
  46118. this._ranges = {};
  46119. this.targetPropertyPath = targetProperty.split(".");
  46120. this.dataType = dataType;
  46121. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46122. }
  46123. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46124. var dataType = undefined;
  46125. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46126. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46127. }
  46128. else if (from instanceof BABYLON.Quaternion) {
  46129. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46130. }
  46131. else if (from instanceof BABYLON.Vector3) {
  46132. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46133. }
  46134. else if (from instanceof BABYLON.Vector2) {
  46135. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46136. }
  46137. else if (from instanceof BABYLON.Color3) {
  46138. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46139. }
  46140. else if (from instanceof BABYLON.Size) {
  46141. dataType = Animation.ANIMATIONTYPE_SIZE;
  46142. }
  46143. if (dataType == undefined) {
  46144. return null;
  46145. }
  46146. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46147. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46148. animation.setKeys(keys);
  46149. if (easingFunction !== undefined) {
  46150. animation.setEasingFunction(easingFunction);
  46151. }
  46152. return animation;
  46153. };
  46154. /**
  46155. * Sets up an animation.
  46156. * @param property the property to animate
  46157. * @param animationType the animation type to apply
  46158. * @param easingFunction the easing function used in the animation
  46159. * @returns The created animation
  46160. */
  46161. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46162. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46163. animation.setEasingFunction(easingFunction);
  46164. return animation;
  46165. };
  46166. /**
  46167. * Create and start an animation on a node
  46168. * @param {string} name defines the name of the global animation that will be run on all nodes
  46169. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46170. * @param {string} targetProperty defines property to animate
  46171. * @param {number} framePerSecond defines the number of frame per second yo use
  46172. * @param {number} totalFrame defines the number of frames in total
  46173. * @param {any} from defines the initial value
  46174. * @param {any} to defines the final value
  46175. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46176. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46177. * @param onAnimationEnd defines the callback to call when animation end
  46178. * @returns the animatable created for this animation
  46179. */
  46180. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46181. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46182. if (!animation) {
  46183. return null;
  46184. }
  46185. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46186. };
  46187. /**
  46188. * Create and start an animation on a node and its descendants
  46189. * @param {string} name defines the name of the global animation that will be run on all nodes
  46190. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46191. * @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.
  46192. * @param {string} targetProperty defines property to animate
  46193. * @param {number} framePerSecond defines the number of frame per second yo use
  46194. * @param {number} totalFrame defines the number of frames in total
  46195. * @param {any} from defines the initial value
  46196. * @param {any} to defines the final value
  46197. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46198. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46199. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46200. * @returns the list of animatables created for all nodes
  46201. * @example https://www.babylonjs-playground.com/#MH0VLI
  46202. */
  46203. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46204. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46205. if (!animation) {
  46206. return null;
  46207. }
  46208. var scene = node.getScene();
  46209. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46210. };
  46211. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46212. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46213. if (!animation) {
  46214. return null;
  46215. }
  46216. node.animations.push(animation);
  46217. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46218. };
  46219. /**
  46220. * Transition property of the Camera to the target Value.
  46221. * @param property The property to transition
  46222. * @param targetValue The target Value of the property
  46223. * @param host The object where the property to animate belongs
  46224. * @param scene Scene used to run the animation
  46225. * @param frameRate Framerate (in frame/s) to use
  46226. * @param transition The transition type we want to use
  46227. * @param duration The duration of the animation, in milliseconds
  46228. * @param onAnimationEnd Call back trigger at the end of the animation.
  46229. */
  46230. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46231. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46232. if (duration <= 0) {
  46233. host[property] = targetValue;
  46234. if (onAnimationEnd) {
  46235. onAnimationEnd();
  46236. }
  46237. return null;
  46238. }
  46239. var endFrame = frameRate * (duration / 1000);
  46240. transition.setKeys([{
  46241. frame: 0,
  46242. value: host[property].clone ? host[property].clone() : host[property]
  46243. },
  46244. {
  46245. frame: endFrame,
  46246. value: targetValue
  46247. }]);
  46248. if (!host.animations) {
  46249. host.animations = [];
  46250. }
  46251. host.animations.push(transition);
  46252. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46253. animation.onAnimationEnd = onAnimationEnd;
  46254. return animation;
  46255. };
  46256. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46257. /**
  46258. * Return the array of runtime animations currently using this animation
  46259. */
  46260. get: function () {
  46261. return this._runtimeAnimations;
  46262. },
  46263. enumerable: true,
  46264. configurable: true
  46265. });
  46266. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46267. get: function () {
  46268. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46269. var runtimeAnimation = _a[_i];
  46270. if (!runtimeAnimation.isStopped) {
  46271. return true;
  46272. }
  46273. }
  46274. return false;
  46275. },
  46276. enumerable: true,
  46277. configurable: true
  46278. });
  46279. // Methods
  46280. /**
  46281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46282. */
  46283. Animation.prototype.toString = function (fullDetails) {
  46284. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46285. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46286. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46287. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46288. if (fullDetails) {
  46289. ret += ", Ranges: {";
  46290. var first = true;
  46291. for (var name in this._ranges) {
  46292. if (first) {
  46293. ret += ", ";
  46294. first = false;
  46295. }
  46296. ret += name;
  46297. }
  46298. ret += "}";
  46299. }
  46300. return ret;
  46301. };
  46302. /**
  46303. * Add an event to this animation.
  46304. */
  46305. Animation.prototype.addEvent = function (event) {
  46306. this._events.push(event);
  46307. };
  46308. /**
  46309. * Remove all events found at the given frame
  46310. * @param frame
  46311. */
  46312. Animation.prototype.removeEvents = function (frame) {
  46313. for (var index = 0; index < this._events.length; index++) {
  46314. if (this._events[index].frame === frame) {
  46315. this._events.splice(index, 1);
  46316. index--;
  46317. }
  46318. }
  46319. };
  46320. Animation.prototype.getEvents = function () {
  46321. return this._events;
  46322. };
  46323. Animation.prototype.createRange = function (name, from, to) {
  46324. // check name not already in use; could happen for bones after serialized
  46325. if (!this._ranges[name]) {
  46326. this._ranges[name] = new AnimationRange(name, from, to);
  46327. }
  46328. };
  46329. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46330. if (deleteFrames === void 0) { deleteFrames = true; }
  46331. var range = this._ranges[name];
  46332. if (!range) {
  46333. return;
  46334. }
  46335. if (deleteFrames) {
  46336. var from = range.from;
  46337. var to = range.to;
  46338. // this loop MUST go high to low for multiple splices to work
  46339. for (var key = this._keys.length - 1; key >= 0; key--) {
  46340. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46341. this._keys.splice(key, 1);
  46342. }
  46343. }
  46344. }
  46345. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46346. };
  46347. Animation.prototype.getRange = function (name) {
  46348. return this._ranges[name];
  46349. };
  46350. Animation.prototype.getKeys = function () {
  46351. return this._keys;
  46352. };
  46353. Animation.prototype.getHighestFrame = function () {
  46354. var ret = 0;
  46355. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46356. if (ret < this._keys[key].frame) {
  46357. ret = this._keys[key].frame;
  46358. }
  46359. }
  46360. return ret;
  46361. };
  46362. Animation.prototype.getEasingFunction = function () {
  46363. return this._easingFunction;
  46364. };
  46365. Animation.prototype.setEasingFunction = function (easingFunction) {
  46366. this._easingFunction = easingFunction;
  46367. };
  46368. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46369. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46370. };
  46371. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46372. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46373. };
  46374. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46375. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46376. };
  46377. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46378. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46379. };
  46380. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46381. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46382. };
  46383. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46384. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46385. };
  46386. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46387. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46388. };
  46389. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46390. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46391. };
  46392. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46393. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46394. };
  46395. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46396. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46397. };
  46398. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46399. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46400. };
  46401. Animation.prototype.clone = function () {
  46402. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46403. clone.enableBlending = this.enableBlending;
  46404. clone.blendingSpeed = this.blendingSpeed;
  46405. if (this._keys) {
  46406. clone.setKeys(this._keys);
  46407. }
  46408. if (this._ranges) {
  46409. clone._ranges = {};
  46410. for (var name in this._ranges) {
  46411. var range = this._ranges[name];
  46412. if (!range) {
  46413. continue;
  46414. }
  46415. clone._ranges[name] = range.clone();
  46416. }
  46417. }
  46418. return clone;
  46419. };
  46420. Animation.prototype.setKeys = function (values) {
  46421. this._keys = values.slice(0);
  46422. };
  46423. Animation.prototype.serialize = function () {
  46424. var serializationObject = {};
  46425. serializationObject.name = this.name;
  46426. serializationObject.property = this.targetProperty;
  46427. serializationObject.framePerSecond = this.framePerSecond;
  46428. serializationObject.dataType = this.dataType;
  46429. serializationObject.loopBehavior = this.loopMode;
  46430. serializationObject.enableBlending = this.enableBlending;
  46431. serializationObject.blendingSpeed = this.blendingSpeed;
  46432. var dataType = this.dataType;
  46433. serializationObject.keys = [];
  46434. var keys = this.getKeys();
  46435. for (var index = 0; index < keys.length; index++) {
  46436. var animationKey = keys[index];
  46437. var key = {};
  46438. key.frame = animationKey.frame;
  46439. switch (dataType) {
  46440. case Animation.ANIMATIONTYPE_FLOAT:
  46441. key.values = [animationKey.value];
  46442. break;
  46443. case Animation.ANIMATIONTYPE_QUATERNION:
  46444. case Animation.ANIMATIONTYPE_MATRIX:
  46445. case Animation.ANIMATIONTYPE_VECTOR3:
  46446. case Animation.ANIMATIONTYPE_COLOR3:
  46447. key.values = animationKey.value.asArray();
  46448. break;
  46449. }
  46450. serializationObject.keys.push(key);
  46451. }
  46452. serializationObject.ranges = [];
  46453. for (var name in this._ranges) {
  46454. var source = this._ranges[name];
  46455. if (!source) {
  46456. continue;
  46457. }
  46458. var range = {};
  46459. range.name = name;
  46460. range.from = source.from;
  46461. range.to = source.to;
  46462. serializationObject.ranges.push(range);
  46463. }
  46464. return serializationObject;
  46465. };
  46466. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46467. get: function () {
  46468. return Animation._ANIMATIONTYPE_FLOAT;
  46469. },
  46470. enumerable: true,
  46471. configurable: true
  46472. });
  46473. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46474. get: function () {
  46475. return Animation._ANIMATIONTYPE_VECTOR3;
  46476. },
  46477. enumerable: true,
  46478. configurable: true
  46479. });
  46480. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46481. get: function () {
  46482. return Animation._ANIMATIONTYPE_VECTOR2;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46488. get: function () {
  46489. return Animation._ANIMATIONTYPE_SIZE;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46495. get: function () {
  46496. return Animation._ANIMATIONTYPE_QUATERNION;
  46497. },
  46498. enumerable: true,
  46499. configurable: true
  46500. });
  46501. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46502. get: function () {
  46503. return Animation._ANIMATIONTYPE_MATRIX;
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46509. get: function () {
  46510. return Animation._ANIMATIONTYPE_COLOR3;
  46511. },
  46512. enumerable: true,
  46513. configurable: true
  46514. });
  46515. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46516. get: function () {
  46517. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46518. },
  46519. enumerable: true,
  46520. configurable: true
  46521. });
  46522. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46523. get: function () {
  46524. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46530. get: function () {
  46531. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Animation.Parse = function (parsedAnimation) {
  46537. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46538. var dataType = parsedAnimation.dataType;
  46539. var keys = [];
  46540. var data;
  46541. var index;
  46542. if (parsedAnimation.enableBlending) {
  46543. animation.enableBlending = parsedAnimation.enableBlending;
  46544. }
  46545. if (parsedAnimation.blendingSpeed) {
  46546. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46547. }
  46548. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46549. var key = parsedAnimation.keys[index];
  46550. var inTangent;
  46551. var outTangent;
  46552. switch (dataType) {
  46553. case Animation.ANIMATIONTYPE_FLOAT:
  46554. data = key.values[0];
  46555. if (key.values.length >= 1) {
  46556. inTangent = key.values[1];
  46557. }
  46558. if (key.values.length >= 2) {
  46559. outTangent = key.values[2];
  46560. }
  46561. break;
  46562. case Animation.ANIMATIONTYPE_QUATERNION:
  46563. data = BABYLON.Quaternion.FromArray(key.values);
  46564. if (key.values.length >= 8) {
  46565. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46566. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46567. inTangent = _inTangent;
  46568. }
  46569. }
  46570. if (key.values.length >= 12) {
  46571. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46572. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46573. outTangent = _outTangent;
  46574. }
  46575. }
  46576. break;
  46577. case Animation.ANIMATIONTYPE_MATRIX:
  46578. data = BABYLON.Matrix.FromArray(key.values);
  46579. break;
  46580. case Animation.ANIMATIONTYPE_COLOR3:
  46581. data = BABYLON.Color3.FromArray(key.values);
  46582. break;
  46583. case Animation.ANIMATIONTYPE_VECTOR3:
  46584. default:
  46585. data = BABYLON.Vector3.FromArray(key.values);
  46586. break;
  46587. }
  46588. var keyData = {};
  46589. keyData.frame = key.frame;
  46590. keyData.value = data;
  46591. if (inTangent != undefined) {
  46592. keyData.inTangent = inTangent;
  46593. }
  46594. if (outTangent != undefined) {
  46595. keyData.outTangent = outTangent;
  46596. }
  46597. keys.push(keyData);
  46598. }
  46599. animation.setKeys(keys);
  46600. if (parsedAnimation.ranges) {
  46601. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46602. data = parsedAnimation.ranges[index];
  46603. animation.createRange(data.name, data.from, data.to);
  46604. }
  46605. }
  46606. return animation;
  46607. };
  46608. Animation.AppendSerializedAnimations = function (source, destination) {
  46609. if (source.animations) {
  46610. destination.animations = [];
  46611. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46612. var animation = source.animations[animationIndex];
  46613. destination.animations.push(animation.serialize());
  46614. }
  46615. }
  46616. };
  46617. Animation.AllowMatricesInterpolation = false;
  46618. // Statics
  46619. Animation._ANIMATIONTYPE_FLOAT = 0;
  46620. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46621. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46622. Animation._ANIMATIONTYPE_MATRIX = 3;
  46623. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46624. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46625. Animation._ANIMATIONTYPE_SIZE = 6;
  46626. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46627. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46628. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46629. return Animation;
  46630. }());
  46631. BABYLON.Animation = Animation;
  46632. })(BABYLON || (BABYLON = {}));
  46633. //# sourceMappingURL=babylon.animation.js.map
  46634. var BABYLON;
  46635. (function (BABYLON) {
  46636. /**
  46637. * This class defines the direct association between an animation and a target
  46638. */
  46639. var TargetedAnimation = /** @class */ (function () {
  46640. function TargetedAnimation() {
  46641. }
  46642. return TargetedAnimation;
  46643. }());
  46644. BABYLON.TargetedAnimation = TargetedAnimation;
  46645. /**
  46646. * Use this class to create coordinated animations on multiple targets
  46647. */
  46648. var AnimationGroup = /** @class */ (function () {
  46649. function AnimationGroup(name, scene) {
  46650. if (scene === void 0) { scene = null; }
  46651. this.name = name;
  46652. this._targetedAnimations = new Array();
  46653. this._animatables = new Array();
  46654. this._from = Number.MAX_VALUE;
  46655. this._to = -Number.MAX_VALUE;
  46656. this._speedRatio = 1;
  46657. this.onAnimationEndObservable = new BABYLON.Observable();
  46658. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46659. this._scene.animationGroups.push(this);
  46660. }
  46661. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46662. /**
  46663. * Define if the animations are started
  46664. */
  46665. get: function () {
  46666. return this._isStarted;
  46667. },
  46668. enumerable: true,
  46669. configurable: true
  46670. });
  46671. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46672. /**
  46673. * Gets or sets the speed ratio to use for all animations
  46674. */
  46675. get: function () {
  46676. return this._speedRatio;
  46677. },
  46678. /**
  46679. * Gets or sets the speed ratio to use for all animations
  46680. */
  46681. set: function (value) {
  46682. if (this._speedRatio === value) {
  46683. return;
  46684. }
  46685. this._speedRatio = value;
  46686. for (var index = 0; index < this._animatables.length; index++) {
  46687. var animatable = this._animatables[index];
  46688. animatable.speedRatio = this._speedRatio;
  46689. }
  46690. },
  46691. enumerable: true,
  46692. configurable: true
  46693. });
  46694. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46695. /**
  46696. * Gets the targeted animations for this animation group
  46697. */
  46698. get: function () {
  46699. return this._targetedAnimations;
  46700. },
  46701. enumerable: true,
  46702. configurable: true
  46703. });
  46704. /**
  46705. * Add an animation (with its target) in the group
  46706. * @param animation defines the animation we want to add
  46707. * @param target defines the target of the animation
  46708. * @returns the {BABYLON.TargetedAnimation} object
  46709. */
  46710. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46711. var targetedAnimation = {
  46712. animation: animation,
  46713. target: target
  46714. };
  46715. var keys = animation.getKeys();
  46716. if (this._from > keys[0].frame) {
  46717. this._from = keys[0].frame;
  46718. }
  46719. if (this._to < keys[keys.length - 1].frame) {
  46720. this._to = keys[keys.length - 1].frame;
  46721. }
  46722. this._targetedAnimations.push(targetedAnimation);
  46723. return targetedAnimation;
  46724. };
  46725. /**
  46726. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46727. * It can add constant keys at begin or end
  46728. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46729. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46730. */
  46731. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46732. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46733. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46734. beginFrame = Math.max(beginFrame, this._from);
  46735. endFrame = Math.min(endFrame, this._to);
  46736. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46737. var targetedAnimation = this._targetedAnimations[index];
  46738. var keys = targetedAnimation.animation.getKeys();
  46739. var startKey = keys[0];
  46740. var endKey = keys[keys.length - 1];
  46741. if (startKey.frame > beginFrame) {
  46742. var newKey = {
  46743. frame: beginFrame,
  46744. value: startKey.value,
  46745. inTangent: startKey.inTangent,
  46746. outTangent: startKey.outTangent,
  46747. interpolation: startKey.interpolation
  46748. };
  46749. keys.splice(0, 0, newKey);
  46750. }
  46751. if (endKey.frame < endFrame) {
  46752. var newKey = {
  46753. frame: endFrame,
  46754. value: endKey.value,
  46755. inTangent: endKey.outTangent,
  46756. outTangent: endKey.outTangent,
  46757. interpolation: endKey.interpolation
  46758. };
  46759. keys.push(newKey);
  46760. }
  46761. }
  46762. return this;
  46763. };
  46764. /**
  46765. * Start all animations on given targets
  46766. * @param loop defines if animations must loop
  46767. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46768. */
  46769. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46770. var _this = this;
  46771. if (loop === void 0) { loop = false; }
  46772. if (speedRatio === void 0) { speedRatio = 1; }
  46773. if (this._isStarted || this._targetedAnimations.length === 0) {
  46774. return this;
  46775. }
  46776. var _loop_1 = function () {
  46777. var targetedAnimation = this_1._targetedAnimations[index];
  46778. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46779. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46780. }));
  46781. };
  46782. var this_1 = this;
  46783. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46784. _loop_1();
  46785. }
  46786. this._speedRatio = speedRatio;
  46787. this._isStarted = true;
  46788. return this;
  46789. };
  46790. /**
  46791. * Pause all animations
  46792. */
  46793. AnimationGroup.prototype.pause = function () {
  46794. if (!this._isStarted) {
  46795. return this;
  46796. }
  46797. for (var index = 0; index < this._animatables.length; index++) {
  46798. var animatable = this._animatables[index];
  46799. animatable.pause();
  46800. }
  46801. return this;
  46802. };
  46803. /**
  46804. * Play all animations to initial state
  46805. * This function will start() the animations if they were not started or will restart() them if they were paused
  46806. * @param loop defines if animations must loop
  46807. */
  46808. AnimationGroup.prototype.play = function (loop) {
  46809. if (this.isStarted) {
  46810. if (loop !== undefined) {
  46811. for (var index = 0; index < this._animatables.length; index++) {
  46812. var animatable = this._animatables[index];
  46813. animatable.loopAnimation = loop;
  46814. }
  46815. }
  46816. this.restart();
  46817. }
  46818. else {
  46819. this.start(loop, this._speedRatio);
  46820. }
  46821. return this;
  46822. };
  46823. /**
  46824. * Reset all animations to initial state
  46825. */
  46826. AnimationGroup.prototype.reset = function () {
  46827. if (!this._isStarted) {
  46828. return this;
  46829. }
  46830. for (var index = 0; index < this._animatables.length; index++) {
  46831. var animatable = this._animatables[index];
  46832. animatable.reset();
  46833. }
  46834. return this;
  46835. };
  46836. /**
  46837. * Restart animations from key 0
  46838. */
  46839. AnimationGroup.prototype.restart = function () {
  46840. if (!this._isStarted) {
  46841. return this;
  46842. }
  46843. for (var index = 0; index < this._animatables.length; index++) {
  46844. var animatable = this._animatables[index];
  46845. animatable.restart();
  46846. }
  46847. return this;
  46848. };
  46849. /**
  46850. * Stop all animations
  46851. */
  46852. AnimationGroup.prototype.stop = function () {
  46853. if (!this._isStarted) {
  46854. return this;
  46855. }
  46856. for (var index = 0; index < this._animatables.length; index++) {
  46857. var animatable = this._animatables[index];
  46858. animatable.stop();
  46859. }
  46860. this._isStarted = false;
  46861. return this;
  46862. };
  46863. /**
  46864. * Dispose all associated resources
  46865. */
  46866. AnimationGroup.prototype.dispose = function () {
  46867. this._targetedAnimations = [];
  46868. this._animatables = [];
  46869. var index = this._scene.animationGroups.indexOf(this);
  46870. if (index > -1) {
  46871. this._scene.animationGroups.splice(index, 1);
  46872. }
  46873. };
  46874. return AnimationGroup;
  46875. }());
  46876. BABYLON.AnimationGroup = AnimationGroup;
  46877. })(BABYLON || (BABYLON = {}));
  46878. //# sourceMappingURL=babylon.animationGroup.js.map
  46879. var BABYLON;
  46880. (function (BABYLON) {
  46881. var RuntimeAnimation = /** @class */ (function () {
  46882. function RuntimeAnimation(target, animation) {
  46883. this._offsetsCache = {};
  46884. this._highLimitsCache = {};
  46885. this._stopped = false;
  46886. this._blendingFactor = 0;
  46887. this._ratioOffset = 0;
  46888. this._animation = animation;
  46889. this._target = target;
  46890. animation._runtimeAnimations.push(this);
  46891. }
  46892. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46893. get: function () {
  46894. return this._animation;
  46895. },
  46896. enumerable: true,
  46897. configurable: true
  46898. });
  46899. RuntimeAnimation.prototype.reset = function () {
  46900. this._offsetsCache = {};
  46901. this._highLimitsCache = {};
  46902. this.currentFrame = 0;
  46903. this._blendingFactor = 0;
  46904. this._originalBlendValue = null;
  46905. };
  46906. RuntimeAnimation.prototype.isStopped = function () {
  46907. return this._stopped;
  46908. };
  46909. RuntimeAnimation.prototype.dispose = function () {
  46910. var index = this._animation.runtimeAnimations.indexOf(this);
  46911. if (index > -1) {
  46912. this._animation.runtimeAnimations.splice(index, 1);
  46913. }
  46914. };
  46915. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46916. if (typeof value === "function") {
  46917. return value();
  46918. }
  46919. return value;
  46920. };
  46921. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46922. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46923. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46924. }
  46925. this.currentFrame = currentFrame;
  46926. var keys = this._animation.getKeys();
  46927. // Try to get a hash to find the right key
  46928. 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));
  46929. if (keys[startKeyIndex].frame >= currentFrame) {
  46930. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46931. startKeyIndex--;
  46932. }
  46933. }
  46934. for (var key = startKeyIndex; key < keys.length; key++) {
  46935. var endKey = keys[key + 1];
  46936. if (endKey.frame >= currentFrame) {
  46937. var startKey = keys[key];
  46938. var startValue = this._getKeyValue(startKey.value);
  46939. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46940. return startValue;
  46941. }
  46942. var endValue = this._getKeyValue(endKey.value);
  46943. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46944. var frameDelta = endKey.frame - startKey.frame;
  46945. // gradient : percent of currentFrame between the frame inf and the frame sup
  46946. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46947. // check for easingFunction and correction of gradient
  46948. var easingFunction = this._animation.getEasingFunction();
  46949. if (easingFunction != null) {
  46950. gradient = easingFunction.ease(gradient);
  46951. }
  46952. switch (this._animation.dataType) {
  46953. // Float
  46954. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46955. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46956. switch (loopMode) {
  46957. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46958. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46959. return floatValue;
  46960. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46961. return offsetValue * repeatCount + floatValue;
  46962. }
  46963. break;
  46964. // Quaternion
  46965. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46966. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46967. switch (loopMode) {
  46968. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46969. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46970. return quatValue;
  46971. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46972. return quatValue.add(offsetValue.scale(repeatCount));
  46973. }
  46974. return quatValue;
  46975. // Vector3
  46976. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46977. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46978. switch (loopMode) {
  46979. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46980. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46981. return vec3Value;
  46982. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46983. return vec3Value.add(offsetValue.scale(repeatCount));
  46984. }
  46985. // Vector2
  46986. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46987. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46988. switch (loopMode) {
  46989. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46990. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46991. return vec2Value;
  46992. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46993. return vec2Value.add(offsetValue.scale(repeatCount));
  46994. }
  46995. // Size
  46996. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46997. switch (loopMode) {
  46998. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46999. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47000. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47001. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47002. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47003. }
  47004. // Color3
  47005. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47006. switch (loopMode) {
  47007. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47008. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47009. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47010. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47011. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47012. }
  47013. // Matrix
  47014. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47015. switch (loopMode) {
  47016. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47017. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47018. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47019. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47020. }
  47021. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47022. return startValue;
  47023. }
  47024. default:
  47025. break;
  47026. }
  47027. break;
  47028. }
  47029. }
  47030. return this._getKeyValue(keys[keys.length - 1].value);
  47031. };
  47032. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47033. if (blend === void 0) { blend = false; }
  47034. // Set value
  47035. var path;
  47036. var destination;
  47037. var targetPropertyPath = this._animation.targetPropertyPath;
  47038. if (targetPropertyPath.length > 1) {
  47039. var property = this._target[targetPropertyPath[0]];
  47040. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47041. property = property[targetPropertyPath[index]];
  47042. }
  47043. path = targetPropertyPath[targetPropertyPath.length - 1];
  47044. destination = property;
  47045. }
  47046. else {
  47047. path = targetPropertyPath[0];
  47048. destination = this._target;
  47049. }
  47050. // Blending
  47051. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  47052. if (!this._originalBlendValue) {
  47053. if (destination[path].clone) {
  47054. this._originalBlendValue = destination[path].clone();
  47055. }
  47056. else {
  47057. this._originalBlendValue = destination[path];
  47058. }
  47059. }
  47060. if (this._originalBlendValue.prototype) {
  47061. if (this._originalBlendValue.prototype.Lerp) {
  47062. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47063. }
  47064. else {
  47065. destination[path] = currentValue;
  47066. }
  47067. }
  47068. else if (this._originalBlendValue.m) {
  47069. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47070. }
  47071. else {
  47072. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47073. }
  47074. this._blendingFactor += this._animation.blendingSpeed;
  47075. }
  47076. else {
  47077. destination[path] = currentValue;
  47078. }
  47079. if (this._target.markAsDirty) {
  47080. this._target.markAsDirty(this._animation.targetProperty);
  47081. }
  47082. };
  47083. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47084. var keys = this._animation.getKeys();
  47085. if (frame < keys[0].frame) {
  47086. frame = keys[0].frame;
  47087. }
  47088. else if (frame > keys[keys.length - 1].frame) {
  47089. frame = keys[keys.length - 1].frame;
  47090. }
  47091. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  47092. this.setValue(currentValue);
  47093. };
  47094. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47095. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47096. this._ratioOffset = this._previousRatio - newRatio;
  47097. };
  47098. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47099. if (blend === void 0) { blend = false; }
  47100. var targetPropertyPath = this._animation.targetPropertyPath;
  47101. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47102. this._stopped = true;
  47103. return false;
  47104. }
  47105. var returnValue = true;
  47106. var keys = this._animation.getKeys();
  47107. // Adding a start key at frame 0 if missing
  47108. if (keys[0].frame !== 0) {
  47109. var newKey = { frame: 0, value: keys[0].value };
  47110. keys.splice(0, 0, newKey);
  47111. }
  47112. // Check limits
  47113. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47114. from = keys[0].frame;
  47115. }
  47116. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47117. to = keys[keys.length - 1].frame;
  47118. }
  47119. //to and from cannot be the same key
  47120. if (from === to) {
  47121. if (from > keys[0].frame) {
  47122. from--;
  47123. }
  47124. else if (to < keys[keys.length - 1].frame) {
  47125. to++;
  47126. }
  47127. }
  47128. // Compute ratio
  47129. var range = to - from;
  47130. var offsetValue;
  47131. // ratio represents the frame delta between from and to
  47132. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47133. var highLimitValue = 0;
  47134. this._previousDelay = delay;
  47135. this._previousRatio = ratio;
  47136. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47137. returnValue = false;
  47138. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47139. }
  47140. else {
  47141. // Get max value if required
  47142. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47143. var keyOffset = to.toString() + from.toString();
  47144. if (!this._offsetsCache[keyOffset]) {
  47145. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47146. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47147. switch (this._animation.dataType) {
  47148. // Float
  47149. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47150. this._offsetsCache[keyOffset] = toValue - fromValue;
  47151. break;
  47152. // Quaternion
  47153. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47154. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47155. break;
  47156. // Vector3
  47157. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47158. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47159. // Vector2
  47160. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47161. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47162. // Size
  47163. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47164. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47165. // Color3
  47166. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47167. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47168. default:
  47169. break;
  47170. }
  47171. this._highLimitsCache[keyOffset] = toValue;
  47172. }
  47173. highLimitValue = this._highLimitsCache[keyOffset];
  47174. offsetValue = this._offsetsCache[keyOffset];
  47175. }
  47176. }
  47177. if (offsetValue === undefined) {
  47178. switch (this._animation.dataType) {
  47179. // Float
  47180. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47181. offsetValue = 0;
  47182. break;
  47183. // Quaternion
  47184. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47185. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47186. break;
  47187. // Vector3
  47188. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47189. offsetValue = BABYLON.Vector3.Zero();
  47190. break;
  47191. // Vector2
  47192. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47193. offsetValue = BABYLON.Vector2.Zero();
  47194. break;
  47195. // Size
  47196. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47197. offsetValue = BABYLON.Size.Zero();
  47198. break;
  47199. // Color3
  47200. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47201. offsetValue = BABYLON.Color3.Black();
  47202. }
  47203. }
  47204. // Compute value
  47205. var repeatCount = (ratio / range) >> 0;
  47206. var currentFrame = returnValue ? from + ratio % range : to;
  47207. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  47208. // Set value
  47209. this.setValue(currentValue);
  47210. // Check events
  47211. var events = this._animation.getEvents();
  47212. for (var index = 0; index < events.length; index++) {
  47213. // Make sure current frame has passed event frame and that event frame is within the current range
  47214. // Also, handle both forward and reverse animations
  47215. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47216. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47217. var event = events[index];
  47218. if (!event.isDone) {
  47219. // If event should be done only once, remove it.
  47220. if (event.onlyOnce) {
  47221. events.splice(index, 1);
  47222. index--;
  47223. }
  47224. event.isDone = true;
  47225. event.action();
  47226. } // Don't do anything if the event has already be done.
  47227. }
  47228. else if (events[index].isDone && !events[index].onlyOnce) {
  47229. // reset event, the animation is looping
  47230. events[index].isDone = false;
  47231. }
  47232. }
  47233. if (!returnValue) {
  47234. this._stopped = true;
  47235. }
  47236. return returnValue;
  47237. };
  47238. return RuntimeAnimation;
  47239. }());
  47240. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47241. })(BABYLON || (BABYLON = {}));
  47242. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47243. var BABYLON;
  47244. (function (BABYLON) {
  47245. var Animatable = /** @class */ (function () {
  47246. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47247. if (fromFrame === void 0) { fromFrame = 0; }
  47248. if (toFrame === void 0) { toFrame = 100; }
  47249. if (loopAnimation === void 0) { loopAnimation = false; }
  47250. if (speedRatio === void 0) { speedRatio = 1.0; }
  47251. this.target = target;
  47252. this.fromFrame = fromFrame;
  47253. this.toFrame = toFrame;
  47254. this.loopAnimation = loopAnimation;
  47255. this.onAnimationEnd = onAnimationEnd;
  47256. this._localDelayOffset = null;
  47257. this._pausedDelay = null;
  47258. this._runtimeAnimations = new Array();
  47259. this._paused = false;
  47260. this._speedRatio = 1;
  47261. this.animationStarted = false;
  47262. if (animations) {
  47263. this.appendAnimations(target, animations);
  47264. }
  47265. this._speedRatio = speedRatio;
  47266. this._scene = scene;
  47267. scene._activeAnimatables.push(this);
  47268. }
  47269. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47270. get: function () {
  47271. return this._speedRatio;
  47272. },
  47273. set: function (value) {
  47274. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47275. var animation = this._runtimeAnimations[index];
  47276. animation._prepareForSpeedRatioChange(value);
  47277. }
  47278. this._speedRatio = value;
  47279. },
  47280. enumerable: true,
  47281. configurable: true
  47282. });
  47283. // Methods
  47284. Animatable.prototype.getAnimations = function () {
  47285. return this._runtimeAnimations;
  47286. };
  47287. Animatable.prototype.appendAnimations = function (target, animations) {
  47288. for (var index = 0; index < animations.length; index++) {
  47289. var animation = animations[index];
  47290. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47291. }
  47292. };
  47293. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47294. var runtimeAnimations = this._runtimeAnimations;
  47295. for (var index = 0; index < runtimeAnimations.length; index++) {
  47296. if (runtimeAnimations[index].animation.targetProperty === property) {
  47297. return runtimeAnimations[index].animation;
  47298. }
  47299. }
  47300. return null;
  47301. };
  47302. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47303. var runtimeAnimations = this._runtimeAnimations;
  47304. for (var index = 0; index < runtimeAnimations.length; index++) {
  47305. if (runtimeAnimations[index].animation.targetProperty === property) {
  47306. return runtimeAnimations[index];
  47307. }
  47308. }
  47309. return null;
  47310. };
  47311. Animatable.prototype.reset = function () {
  47312. var runtimeAnimations = this._runtimeAnimations;
  47313. for (var index = 0; index < runtimeAnimations.length; index++) {
  47314. runtimeAnimations[index].reset();
  47315. }
  47316. // Reset to original value
  47317. for (index = 0; index < runtimeAnimations.length; index++) {
  47318. var animation = runtimeAnimations[index];
  47319. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47320. }
  47321. this._localDelayOffset = null;
  47322. this._pausedDelay = null;
  47323. };
  47324. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47325. var runtimeAnimations = this._runtimeAnimations;
  47326. for (var index = 0; index < runtimeAnimations.length; index++) {
  47327. runtimeAnimations[index].animation.enableBlending = true;
  47328. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47329. }
  47330. };
  47331. Animatable.prototype.disableBlending = function () {
  47332. var runtimeAnimations = this._runtimeAnimations;
  47333. for (var index = 0; index < runtimeAnimations.length; index++) {
  47334. runtimeAnimations[index].animation.enableBlending = false;
  47335. }
  47336. };
  47337. Animatable.prototype.goToFrame = function (frame) {
  47338. var runtimeAnimations = this._runtimeAnimations;
  47339. if (runtimeAnimations[0]) {
  47340. var fps = runtimeAnimations[0].animation.framePerSecond;
  47341. var currentFrame = runtimeAnimations[0].currentFrame;
  47342. var adjustTime = frame - currentFrame;
  47343. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47344. if (this._localDelayOffset === null) {
  47345. this._localDelayOffset = 0;
  47346. }
  47347. this._localDelayOffset -= delay;
  47348. }
  47349. for (var index = 0; index < runtimeAnimations.length; index++) {
  47350. runtimeAnimations[index].goToFrame(frame);
  47351. }
  47352. };
  47353. Animatable.prototype.pause = function () {
  47354. if (this._paused) {
  47355. return;
  47356. }
  47357. this._paused = true;
  47358. };
  47359. Animatable.prototype.restart = function () {
  47360. this._paused = false;
  47361. };
  47362. Animatable.prototype.stop = function (animationName) {
  47363. if (animationName) {
  47364. var idx = this._scene._activeAnimatables.indexOf(this);
  47365. if (idx > -1) {
  47366. var runtimeAnimations = this._runtimeAnimations;
  47367. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47368. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47369. continue;
  47370. }
  47371. runtimeAnimations[index].dispose();
  47372. runtimeAnimations.splice(index, 1);
  47373. }
  47374. if (runtimeAnimations.length == 0) {
  47375. this._scene._activeAnimatables.splice(idx, 1);
  47376. if (this.onAnimationEnd) {
  47377. this.onAnimationEnd();
  47378. }
  47379. }
  47380. }
  47381. }
  47382. else {
  47383. var index = this._scene._activeAnimatables.indexOf(this);
  47384. if (index > -1) {
  47385. this._scene._activeAnimatables.splice(index, 1);
  47386. var runtimeAnimations = this._runtimeAnimations;
  47387. for (var index = 0; index < runtimeAnimations.length; index++) {
  47388. runtimeAnimations[index].dispose();
  47389. }
  47390. if (this.onAnimationEnd) {
  47391. this.onAnimationEnd();
  47392. }
  47393. }
  47394. }
  47395. };
  47396. Animatable.prototype._animate = function (delay) {
  47397. if (this._paused) {
  47398. this.animationStarted = false;
  47399. if (this._pausedDelay === null) {
  47400. this._pausedDelay = delay;
  47401. }
  47402. return true;
  47403. }
  47404. if (this._localDelayOffset === null) {
  47405. this._localDelayOffset = delay;
  47406. this._pausedDelay = null;
  47407. }
  47408. else if (this._pausedDelay !== null) {
  47409. this._localDelayOffset += delay - this._pausedDelay;
  47410. this._pausedDelay = null;
  47411. }
  47412. // Animating
  47413. var running = false;
  47414. var runtimeAnimations = this._runtimeAnimations;
  47415. var index;
  47416. for (index = 0; index < runtimeAnimations.length; index++) {
  47417. var animation = runtimeAnimations[index];
  47418. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47419. running = running || isRunning;
  47420. }
  47421. this.animationStarted = running;
  47422. if (!running) {
  47423. // Remove from active animatables
  47424. index = this._scene._activeAnimatables.indexOf(this);
  47425. this._scene._activeAnimatables.splice(index, 1);
  47426. // Dispose all runtime animations
  47427. for (index = 0; index < runtimeAnimations.length; index++) {
  47428. runtimeAnimations[index].dispose();
  47429. }
  47430. }
  47431. if (!running && this.onAnimationEnd) {
  47432. this.onAnimationEnd();
  47433. this.onAnimationEnd = null;
  47434. }
  47435. return running;
  47436. };
  47437. return Animatable;
  47438. }());
  47439. BABYLON.Animatable = Animatable;
  47440. })(BABYLON || (BABYLON = {}));
  47441. //# sourceMappingURL=babylon.animatable.js.map
  47442. var BABYLON;
  47443. (function (BABYLON) {
  47444. var EasingFunction = /** @class */ (function () {
  47445. function EasingFunction() {
  47446. // Properties
  47447. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47448. }
  47449. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47450. get: function () {
  47451. return EasingFunction._EASINGMODE_EASEIN;
  47452. },
  47453. enumerable: true,
  47454. configurable: true
  47455. });
  47456. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47457. get: function () {
  47458. return EasingFunction._EASINGMODE_EASEOUT;
  47459. },
  47460. enumerable: true,
  47461. configurable: true
  47462. });
  47463. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47464. get: function () {
  47465. return EasingFunction._EASINGMODE_EASEINOUT;
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47471. var n = Math.min(Math.max(easingMode, 0), 2);
  47472. this._easingMode = n;
  47473. };
  47474. EasingFunction.prototype.getEasingMode = function () {
  47475. return this._easingMode;
  47476. };
  47477. EasingFunction.prototype.easeInCore = function (gradient) {
  47478. throw new Error('You must implement this method');
  47479. };
  47480. EasingFunction.prototype.ease = function (gradient) {
  47481. switch (this._easingMode) {
  47482. case EasingFunction.EASINGMODE_EASEIN:
  47483. return this.easeInCore(gradient);
  47484. case EasingFunction.EASINGMODE_EASEOUT:
  47485. return (1 - this.easeInCore(1 - gradient));
  47486. }
  47487. if (gradient >= 0.5) {
  47488. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47489. }
  47490. return (this.easeInCore(gradient * 2) * 0.5);
  47491. };
  47492. //Statics
  47493. EasingFunction._EASINGMODE_EASEIN = 0;
  47494. EasingFunction._EASINGMODE_EASEOUT = 1;
  47495. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47496. return EasingFunction;
  47497. }());
  47498. BABYLON.EasingFunction = EasingFunction;
  47499. var CircleEase = /** @class */ (function (_super) {
  47500. __extends(CircleEase, _super);
  47501. function CircleEase() {
  47502. return _super !== null && _super.apply(this, arguments) || this;
  47503. }
  47504. CircleEase.prototype.easeInCore = function (gradient) {
  47505. gradient = Math.max(0, Math.min(1, gradient));
  47506. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47507. };
  47508. return CircleEase;
  47509. }(EasingFunction));
  47510. BABYLON.CircleEase = CircleEase;
  47511. var BackEase = /** @class */ (function (_super) {
  47512. __extends(BackEase, _super);
  47513. function BackEase(amplitude) {
  47514. if (amplitude === void 0) { amplitude = 1; }
  47515. var _this = _super.call(this) || this;
  47516. _this.amplitude = amplitude;
  47517. return _this;
  47518. }
  47519. BackEase.prototype.easeInCore = function (gradient) {
  47520. var num = Math.max(0, this.amplitude);
  47521. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47522. };
  47523. return BackEase;
  47524. }(EasingFunction));
  47525. BABYLON.BackEase = BackEase;
  47526. var BounceEase = /** @class */ (function (_super) {
  47527. __extends(BounceEase, _super);
  47528. function BounceEase(bounces, bounciness) {
  47529. if (bounces === void 0) { bounces = 3; }
  47530. if (bounciness === void 0) { bounciness = 2; }
  47531. var _this = _super.call(this) || this;
  47532. _this.bounces = bounces;
  47533. _this.bounciness = bounciness;
  47534. return _this;
  47535. }
  47536. BounceEase.prototype.easeInCore = function (gradient) {
  47537. var y = Math.max(0.0, this.bounces);
  47538. var bounciness = this.bounciness;
  47539. if (bounciness <= 1.0) {
  47540. bounciness = 1.001;
  47541. }
  47542. var num9 = Math.pow(bounciness, y);
  47543. var num5 = 1.0 - bounciness;
  47544. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47545. var num15 = gradient * num4;
  47546. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47547. var num3 = Math.floor(num65);
  47548. var num13 = num3 + 1.0;
  47549. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47550. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47551. var num7 = (num8 + num12) * 0.5;
  47552. var num6 = gradient - num7;
  47553. var num2 = num7 - num8;
  47554. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47555. };
  47556. return BounceEase;
  47557. }(EasingFunction));
  47558. BABYLON.BounceEase = BounceEase;
  47559. var CubicEase = /** @class */ (function (_super) {
  47560. __extends(CubicEase, _super);
  47561. function CubicEase() {
  47562. return _super !== null && _super.apply(this, arguments) || this;
  47563. }
  47564. CubicEase.prototype.easeInCore = function (gradient) {
  47565. return (gradient * gradient * gradient);
  47566. };
  47567. return CubicEase;
  47568. }(EasingFunction));
  47569. BABYLON.CubicEase = CubicEase;
  47570. var ElasticEase = /** @class */ (function (_super) {
  47571. __extends(ElasticEase, _super);
  47572. function ElasticEase(oscillations, springiness) {
  47573. if (oscillations === void 0) { oscillations = 3; }
  47574. if (springiness === void 0) { springiness = 3; }
  47575. var _this = _super.call(this) || this;
  47576. _this.oscillations = oscillations;
  47577. _this.springiness = springiness;
  47578. return _this;
  47579. }
  47580. ElasticEase.prototype.easeInCore = function (gradient) {
  47581. var num2;
  47582. var num3 = Math.max(0.0, this.oscillations);
  47583. var num = Math.max(0.0, this.springiness);
  47584. if (num == 0) {
  47585. num2 = gradient;
  47586. }
  47587. else {
  47588. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47589. }
  47590. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47591. };
  47592. return ElasticEase;
  47593. }(EasingFunction));
  47594. BABYLON.ElasticEase = ElasticEase;
  47595. var ExponentialEase = /** @class */ (function (_super) {
  47596. __extends(ExponentialEase, _super);
  47597. function ExponentialEase(exponent) {
  47598. if (exponent === void 0) { exponent = 2; }
  47599. var _this = _super.call(this) || this;
  47600. _this.exponent = exponent;
  47601. return _this;
  47602. }
  47603. ExponentialEase.prototype.easeInCore = function (gradient) {
  47604. if (this.exponent <= 0) {
  47605. return gradient;
  47606. }
  47607. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47608. };
  47609. return ExponentialEase;
  47610. }(EasingFunction));
  47611. BABYLON.ExponentialEase = ExponentialEase;
  47612. var PowerEase = /** @class */ (function (_super) {
  47613. __extends(PowerEase, _super);
  47614. function PowerEase(power) {
  47615. if (power === void 0) { power = 2; }
  47616. var _this = _super.call(this) || this;
  47617. _this.power = power;
  47618. return _this;
  47619. }
  47620. PowerEase.prototype.easeInCore = function (gradient) {
  47621. var y = Math.max(0.0, this.power);
  47622. return Math.pow(gradient, y);
  47623. };
  47624. return PowerEase;
  47625. }(EasingFunction));
  47626. BABYLON.PowerEase = PowerEase;
  47627. var QuadraticEase = /** @class */ (function (_super) {
  47628. __extends(QuadraticEase, _super);
  47629. function QuadraticEase() {
  47630. return _super !== null && _super.apply(this, arguments) || this;
  47631. }
  47632. QuadraticEase.prototype.easeInCore = function (gradient) {
  47633. return (gradient * gradient);
  47634. };
  47635. return QuadraticEase;
  47636. }(EasingFunction));
  47637. BABYLON.QuadraticEase = QuadraticEase;
  47638. var QuarticEase = /** @class */ (function (_super) {
  47639. __extends(QuarticEase, _super);
  47640. function QuarticEase() {
  47641. return _super !== null && _super.apply(this, arguments) || this;
  47642. }
  47643. QuarticEase.prototype.easeInCore = function (gradient) {
  47644. return (gradient * gradient * gradient * gradient);
  47645. };
  47646. return QuarticEase;
  47647. }(EasingFunction));
  47648. BABYLON.QuarticEase = QuarticEase;
  47649. var QuinticEase = /** @class */ (function (_super) {
  47650. __extends(QuinticEase, _super);
  47651. function QuinticEase() {
  47652. return _super !== null && _super.apply(this, arguments) || this;
  47653. }
  47654. QuinticEase.prototype.easeInCore = function (gradient) {
  47655. return (gradient * gradient * gradient * gradient * gradient);
  47656. };
  47657. return QuinticEase;
  47658. }(EasingFunction));
  47659. BABYLON.QuinticEase = QuinticEase;
  47660. var SineEase = /** @class */ (function (_super) {
  47661. __extends(SineEase, _super);
  47662. function SineEase() {
  47663. return _super !== null && _super.apply(this, arguments) || this;
  47664. }
  47665. SineEase.prototype.easeInCore = function (gradient) {
  47666. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47667. };
  47668. return SineEase;
  47669. }(EasingFunction));
  47670. BABYLON.SineEase = SineEase;
  47671. var BezierCurveEase = /** @class */ (function (_super) {
  47672. __extends(BezierCurveEase, _super);
  47673. function BezierCurveEase(x1, y1, x2, y2) {
  47674. if (x1 === void 0) { x1 = 0; }
  47675. if (y1 === void 0) { y1 = 0; }
  47676. if (x2 === void 0) { x2 = 1; }
  47677. if (y2 === void 0) { y2 = 1; }
  47678. var _this = _super.call(this) || this;
  47679. _this.x1 = x1;
  47680. _this.y1 = y1;
  47681. _this.x2 = x2;
  47682. _this.y2 = y2;
  47683. return _this;
  47684. }
  47685. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47686. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47687. };
  47688. return BezierCurveEase;
  47689. }(EasingFunction));
  47690. BABYLON.BezierCurveEase = BezierCurveEase;
  47691. })(BABYLON || (BABYLON = {}));
  47692. //# sourceMappingURL=babylon.easing.js.map
  47693. var BABYLON;
  47694. (function (BABYLON) {
  47695. var Condition = /** @class */ (function () {
  47696. function Condition(actionManager) {
  47697. this._actionManager = actionManager;
  47698. }
  47699. Condition.prototype.isValid = function () {
  47700. return true;
  47701. };
  47702. Condition.prototype._getProperty = function (propertyPath) {
  47703. return this._actionManager._getProperty(propertyPath);
  47704. };
  47705. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47706. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47707. };
  47708. Condition.prototype.serialize = function () {
  47709. };
  47710. Condition.prototype._serialize = function (serializedCondition) {
  47711. return {
  47712. type: 2,
  47713. children: [],
  47714. name: serializedCondition.name,
  47715. properties: serializedCondition.properties
  47716. };
  47717. };
  47718. return Condition;
  47719. }());
  47720. BABYLON.Condition = Condition;
  47721. var ValueCondition = /** @class */ (function (_super) {
  47722. __extends(ValueCondition, _super);
  47723. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47724. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47725. var _this = _super.call(this, actionManager) || this;
  47726. _this.propertyPath = propertyPath;
  47727. _this.value = value;
  47728. _this.operator = operator;
  47729. _this._target = target;
  47730. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47731. _this._property = _this._getProperty(_this.propertyPath);
  47732. return _this;
  47733. }
  47734. Object.defineProperty(ValueCondition, "IsEqual", {
  47735. get: function () {
  47736. return ValueCondition._IsEqual;
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(ValueCondition, "IsDifferent", {
  47742. get: function () {
  47743. return ValueCondition._IsDifferent;
  47744. },
  47745. enumerable: true,
  47746. configurable: true
  47747. });
  47748. Object.defineProperty(ValueCondition, "IsGreater", {
  47749. get: function () {
  47750. return ValueCondition._IsGreater;
  47751. },
  47752. enumerable: true,
  47753. configurable: true
  47754. });
  47755. Object.defineProperty(ValueCondition, "IsLesser", {
  47756. get: function () {
  47757. return ValueCondition._IsLesser;
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. // Methods
  47763. ValueCondition.prototype.isValid = function () {
  47764. switch (this.operator) {
  47765. case ValueCondition.IsGreater:
  47766. return this._effectiveTarget[this._property] > this.value;
  47767. case ValueCondition.IsLesser:
  47768. return this._effectiveTarget[this._property] < this.value;
  47769. case ValueCondition.IsEqual:
  47770. case ValueCondition.IsDifferent:
  47771. var check;
  47772. if (this.value.equals) {
  47773. check = this.value.equals(this._effectiveTarget[this._property]);
  47774. }
  47775. else {
  47776. check = this.value === this._effectiveTarget[this._property];
  47777. }
  47778. return this.operator === ValueCondition.IsEqual ? check : !check;
  47779. }
  47780. return false;
  47781. };
  47782. ValueCondition.prototype.serialize = function () {
  47783. return this._serialize({
  47784. name: "ValueCondition",
  47785. properties: [
  47786. BABYLON.Action._GetTargetProperty(this._target),
  47787. { name: "propertyPath", value: this.propertyPath },
  47788. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47789. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47790. ]
  47791. });
  47792. };
  47793. ValueCondition.GetOperatorName = function (operator) {
  47794. switch (operator) {
  47795. case ValueCondition._IsEqual: return "IsEqual";
  47796. case ValueCondition._IsDifferent: return "IsDifferent";
  47797. case ValueCondition._IsGreater: return "IsGreater";
  47798. case ValueCondition._IsLesser: return "IsLesser";
  47799. default: return "";
  47800. }
  47801. };
  47802. // Statics
  47803. ValueCondition._IsEqual = 0;
  47804. ValueCondition._IsDifferent = 1;
  47805. ValueCondition._IsGreater = 2;
  47806. ValueCondition._IsLesser = 3;
  47807. return ValueCondition;
  47808. }(Condition));
  47809. BABYLON.ValueCondition = ValueCondition;
  47810. var PredicateCondition = /** @class */ (function (_super) {
  47811. __extends(PredicateCondition, _super);
  47812. function PredicateCondition(actionManager, predicate) {
  47813. var _this = _super.call(this, actionManager) || this;
  47814. _this.predicate = predicate;
  47815. return _this;
  47816. }
  47817. PredicateCondition.prototype.isValid = function () {
  47818. return this.predicate();
  47819. };
  47820. return PredicateCondition;
  47821. }(Condition));
  47822. BABYLON.PredicateCondition = PredicateCondition;
  47823. var StateCondition = /** @class */ (function (_super) {
  47824. __extends(StateCondition, _super);
  47825. function StateCondition(actionManager, target, value) {
  47826. var _this = _super.call(this, actionManager) || this;
  47827. _this.value = value;
  47828. _this._target = target;
  47829. return _this;
  47830. }
  47831. // Methods
  47832. StateCondition.prototype.isValid = function () {
  47833. return this._target.state === this.value;
  47834. };
  47835. StateCondition.prototype.serialize = function () {
  47836. return this._serialize({
  47837. name: "StateCondition",
  47838. properties: [
  47839. BABYLON.Action._GetTargetProperty(this._target),
  47840. { name: "value", value: this.value }
  47841. ]
  47842. });
  47843. };
  47844. return StateCondition;
  47845. }(Condition));
  47846. BABYLON.StateCondition = StateCondition;
  47847. })(BABYLON || (BABYLON = {}));
  47848. //# sourceMappingURL=babylon.condition.js.map
  47849. var BABYLON;
  47850. (function (BABYLON) {
  47851. var Action = /** @class */ (function () {
  47852. function Action(triggerOptions, condition) {
  47853. this.triggerOptions = triggerOptions;
  47854. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47855. if (triggerOptions.parameter) {
  47856. this.trigger = triggerOptions.trigger;
  47857. this._triggerParameter = triggerOptions.parameter;
  47858. }
  47859. else {
  47860. this.trigger = triggerOptions;
  47861. }
  47862. this._nextActiveAction = this;
  47863. this._condition = condition;
  47864. }
  47865. // Methods
  47866. Action.prototype._prepare = function () {
  47867. };
  47868. Action.prototype.getTriggerParameter = function () {
  47869. return this._triggerParameter;
  47870. };
  47871. Action.prototype._executeCurrent = function (evt) {
  47872. if (this._nextActiveAction._condition) {
  47873. var condition = this._nextActiveAction._condition;
  47874. var currentRenderId = this._actionManager.getScene().getRenderId();
  47875. // We cache the current evaluation for the current frame
  47876. if (condition._evaluationId === currentRenderId) {
  47877. if (!condition._currentResult) {
  47878. return;
  47879. }
  47880. }
  47881. else {
  47882. condition._evaluationId = currentRenderId;
  47883. if (!condition.isValid()) {
  47884. condition._currentResult = false;
  47885. return;
  47886. }
  47887. condition._currentResult = true;
  47888. }
  47889. }
  47890. this.onBeforeExecuteObservable.notifyObservers(this);
  47891. this._nextActiveAction.execute(evt);
  47892. this.skipToNextActiveAction();
  47893. };
  47894. Action.prototype.execute = function (evt) {
  47895. };
  47896. Action.prototype.skipToNextActiveAction = function () {
  47897. if (this._nextActiveAction._child) {
  47898. if (!this._nextActiveAction._child._actionManager) {
  47899. this._nextActiveAction._child._actionManager = this._actionManager;
  47900. }
  47901. this._nextActiveAction = this._nextActiveAction._child;
  47902. }
  47903. else {
  47904. this._nextActiveAction = this;
  47905. }
  47906. };
  47907. Action.prototype.then = function (action) {
  47908. this._child = action;
  47909. action._actionManager = this._actionManager;
  47910. action._prepare();
  47911. return action;
  47912. };
  47913. Action.prototype._getProperty = function (propertyPath) {
  47914. return this._actionManager._getProperty(propertyPath);
  47915. };
  47916. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47917. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47918. };
  47919. Action.prototype.serialize = function (parent) {
  47920. };
  47921. // Called by BABYLON.Action objects in serialize(...). Internal use
  47922. Action.prototype._serialize = function (serializedAction, parent) {
  47923. var serializationObject = {
  47924. type: 1,
  47925. children: [],
  47926. name: serializedAction.name,
  47927. properties: serializedAction.properties || []
  47928. };
  47929. // Serialize child
  47930. if (this._child) {
  47931. this._child.serialize(serializationObject);
  47932. }
  47933. // Check if "this" has a condition
  47934. if (this._condition) {
  47935. var serializedCondition = this._condition.serialize();
  47936. serializedCondition.children.push(serializationObject);
  47937. if (parent) {
  47938. parent.children.push(serializedCondition);
  47939. }
  47940. return serializedCondition;
  47941. }
  47942. if (parent) {
  47943. parent.children.push(serializationObject);
  47944. }
  47945. return serializationObject;
  47946. };
  47947. Action._SerializeValueAsString = function (value) {
  47948. if (typeof value === "number") {
  47949. return value.toString();
  47950. }
  47951. if (typeof value === "boolean") {
  47952. return value ? "true" : "false";
  47953. }
  47954. if (value instanceof BABYLON.Vector2) {
  47955. return value.x + ", " + value.y;
  47956. }
  47957. if (value instanceof BABYLON.Vector3) {
  47958. return value.x + ", " + value.y + ", " + value.z;
  47959. }
  47960. if (value instanceof BABYLON.Color3) {
  47961. return value.r + ", " + value.g + ", " + value.b;
  47962. }
  47963. if (value instanceof BABYLON.Color4) {
  47964. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47965. }
  47966. return value; // string
  47967. };
  47968. Action._GetTargetProperty = function (target) {
  47969. return {
  47970. name: "target",
  47971. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47972. : target instanceof BABYLON.Light ? "LightProperties"
  47973. : target instanceof BABYLON.Camera ? "CameraProperties"
  47974. : "SceneProperties",
  47975. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47976. };
  47977. };
  47978. return Action;
  47979. }());
  47980. BABYLON.Action = Action;
  47981. })(BABYLON || (BABYLON = {}));
  47982. //# sourceMappingURL=babylon.action.js.map
  47983. var BABYLON;
  47984. (function (BABYLON) {
  47985. /**
  47986. * ActionEvent is the event beint sent when an action is triggered.
  47987. */
  47988. var ActionEvent = /** @class */ (function () {
  47989. /**
  47990. * @param source The mesh or sprite that triggered the action.
  47991. * @param pointerX The X mouse cursor position at the time of the event
  47992. * @param pointerY The Y mouse cursor position at the time of the event
  47993. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47994. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47995. */
  47996. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47997. this.source = source;
  47998. this.pointerX = pointerX;
  47999. this.pointerY = pointerY;
  48000. this.meshUnderPointer = meshUnderPointer;
  48001. this.sourceEvent = sourceEvent;
  48002. this.additionalData = additionalData;
  48003. }
  48004. /**
  48005. * Helper function to auto-create an ActionEvent from a source mesh.
  48006. * @param source The source mesh that triggered the event
  48007. * @param evt {Event} The original (browser) event
  48008. */
  48009. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48010. var scene = source.getScene();
  48011. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48012. };
  48013. /**
  48014. * Helper function to auto-create an ActionEvent from a source mesh.
  48015. * @param source The source sprite that triggered the event
  48016. * @param scene Scene associated with the sprite
  48017. * @param evt {Event} The original (browser) event
  48018. */
  48019. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48020. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48021. };
  48022. /**
  48023. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48024. * @param scene the scene where the event occurred
  48025. * @param evt {Event} The original (browser) event
  48026. */
  48027. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48028. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48029. };
  48030. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48031. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48032. };
  48033. return ActionEvent;
  48034. }());
  48035. BABYLON.ActionEvent = ActionEvent;
  48036. /**
  48037. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48038. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48039. */
  48040. var ActionManager = /** @class */ (function () {
  48041. function ActionManager(scene) {
  48042. // Members
  48043. this.actions = new Array();
  48044. this.hoverCursor = '';
  48045. this._scene = scene;
  48046. scene._actionManagers.push(this);
  48047. }
  48048. Object.defineProperty(ActionManager, "NothingTrigger", {
  48049. get: function () {
  48050. return ActionManager._NothingTrigger;
  48051. },
  48052. enumerable: true,
  48053. configurable: true
  48054. });
  48055. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48056. get: function () {
  48057. return ActionManager._OnPickTrigger;
  48058. },
  48059. enumerable: true,
  48060. configurable: true
  48061. });
  48062. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48063. get: function () {
  48064. return ActionManager._OnLeftPickTrigger;
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48070. get: function () {
  48071. return ActionManager._OnRightPickTrigger;
  48072. },
  48073. enumerable: true,
  48074. configurable: true
  48075. });
  48076. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48077. get: function () {
  48078. return ActionManager._OnCenterPickTrigger;
  48079. },
  48080. enumerable: true,
  48081. configurable: true
  48082. });
  48083. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48084. get: function () {
  48085. return ActionManager._OnPickDownTrigger;
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48091. get: function () {
  48092. return ActionManager._OnDoublePickTrigger;
  48093. },
  48094. enumerable: true,
  48095. configurable: true
  48096. });
  48097. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48098. get: function () {
  48099. return ActionManager._OnPickUpTrigger;
  48100. },
  48101. enumerable: true,
  48102. configurable: true
  48103. });
  48104. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48105. /// This trigger will only be raised if you also declared a OnPickDown
  48106. get: function () {
  48107. return ActionManager._OnPickOutTrigger;
  48108. },
  48109. enumerable: true,
  48110. configurable: true
  48111. });
  48112. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48113. get: function () {
  48114. return ActionManager._OnLongPressTrigger;
  48115. },
  48116. enumerable: true,
  48117. configurable: true
  48118. });
  48119. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48120. get: function () {
  48121. return ActionManager._OnPointerOverTrigger;
  48122. },
  48123. enumerable: true,
  48124. configurable: true
  48125. });
  48126. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48127. get: function () {
  48128. return ActionManager._OnPointerOutTrigger;
  48129. },
  48130. enumerable: true,
  48131. configurable: true
  48132. });
  48133. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48134. get: function () {
  48135. return ActionManager._OnEveryFrameTrigger;
  48136. },
  48137. enumerable: true,
  48138. configurable: true
  48139. });
  48140. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48141. get: function () {
  48142. return ActionManager._OnIntersectionEnterTrigger;
  48143. },
  48144. enumerable: true,
  48145. configurable: true
  48146. });
  48147. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48148. get: function () {
  48149. return ActionManager._OnIntersectionExitTrigger;
  48150. },
  48151. enumerable: true,
  48152. configurable: true
  48153. });
  48154. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48155. get: function () {
  48156. return ActionManager._OnKeyDownTrigger;
  48157. },
  48158. enumerable: true,
  48159. configurable: true
  48160. });
  48161. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48162. get: function () {
  48163. return ActionManager._OnKeyUpTrigger;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. // Methods
  48169. ActionManager.prototype.dispose = function () {
  48170. var index = this._scene._actionManagers.indexOf(this);
  48171. for (var i = 0; i < this.actions.length; i++) {
  48172. var action = this.actions[i];
  48173. ActionManager.Triggers[action.trigger]--;
  48174. if (ActionManager.Triggers[action.trigger] === 0) {
  48175. delete ActionManager.Triggers[action.trigger];
  48176. }
  48177. }
  48178. if (index > -1) {
  48179. this._scene._actionManagers.splice(index, 1);
  48180. }
  48181. };
  48182. ActionManager.prototype.getScene = function () {
  48183. return this._scene;
  48184. };
  48185. /**
  48186. * Does this action manager handles actions of any of the given triggers
  48187. * @param {number[]} triggers - the triggers to be tested
  48188. * @return {boolean} whether one (or more) of the triggers is handeled
  48189. */
  48190. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48191. for (var index = 0; index < this.actions.length; index++) {
  48192. var action = this.actions[index];
  48193. if (triggers.indexOf(action.trigger) > -1) {
  48194. return true;
  48195. }
  48196. }
  48197. return false;
  48198. };
  48199. /**
  48200. * Does this action manager handles actions of a given trigger
  48201. * @param {number} trigger - the trigger to be tested
  48202. * @return {boolean} whether the trigger is handeled
  48203. */
  48204. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48205. for (var index = 0; index < this.actions.length; index++) {
  48206. var action = this.actions[index];
  48207. if (action.trigger === trigger) {
  48208. return true;
  48209. }
  48210. }
  48211. return false;
  48212. };
  48213. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48214. /**
  48215. * Does this action manager has pointer triggers
  48216. * @return {boolean} whether or not it has pointer triggers
  48217. */
  48218. get: function () {
  48219. for (var index = 0; index < this.actions.length; index++) {
  48220. var action = this.actions[index];
  48221. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48222. return true;
  48223. }
  48224. }
  48225. return false;
  48226. },
  48227. enumerable: true,
  48228. configurable: true
  48229. });
  48230. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48231. /**
  48232. * Does this action manager has pick triggers
  48233. * @return {boolean} whether or not it has pick triggers
  48234. */
  48235. get: function () {
  48236. for (var index = 0; index < this.actions.length; index++) {
  48237. var action = this.actions[index];
  48238. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48239. return true;
  48240. }
  48241. }
  48242. return false;
  48243. },
  48244. enumerable: true,
  48245. configurable: true
  48246. });
  48247. Object.defineProperty(ActionManager, "HasTriggers", {
  48248. /**
  48249. * Does exist one action manager with at least one trigger
  48250. * @return {boolean} whether or not it exists one action manager with one trigger
  48251. **/
  48252. get: function () {
  48253. for (var t in ActionManager.Triggers) {
  48254. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48255. return true;
  48256. }
  48257. }
  48258. return false;
  48259. },
  48260. enumerable: true,
  48261. configurable: true
  48262. });
  48263. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48264. /**
  48265. * Does exist one action manager with at least one pick trigger
  48266. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48267. **/
  48268. get: function () {
  48269. for (var t in ActionManager.Triggers) {
  48270. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48271. var t_int = parseInt(t);
  48272. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48273. return true;
  48274. }
  48275. }
  48276. }
  48277. return false;
  48278. },
  48279. enumerable: true,
  48280. configurable: true
  48281. });
  48282. /**
  48283. * Does exist one action manager that handles actions of a given trigger
  48284. * @param {number} trigger - the trigger to be tested
  48285. * @return {boolean} whether the trigger is handeled by at least one action manager
  48286. **/
  48287. ActionManager.HasSpecificTrigger = function (trigger) {
  48288. for (var t in ActionManager.Triggers) {
  48289. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48290. var t_int = parseInt(t);
  48291. if (t_int === trigger) {
  48292. return true;
  48293. }
  48294. }
  48295. }
  48296. return false;
  48297. };
  48298. /**
  48299. * Registers an action to this action manager
  48300. * @param {BABYLON.Action} action - the action to be registered
  48301. * @return {BABYLON.Action} the action amended (prepared) after registration
  48302. */
  48303. ActionManager.prototype.registerAction = function (action) {
  48304. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48305. if (this.getScene().actionManager !== this) {
  48306. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48307. return null;
  48308. }
  48309. }
  48310. this.actions.push(action);
  48311. if (ActionManager.Triggers[action.trigger]) {
  48312. ActionManager.Triggers[action.trigger]++;
  48313. }
  48314. else {
  48315. ActionManager.Triggers[action.trigger] = 1;
  48316. }
  48317. action._actionManager = this;
  48318. action._prepare();
  48319. return action;
  48320. };
  48321. /**
  48322. * Unregisters an action to this action manager
  48323. * @param action The action to be unregistered
  48324. * @return whether the action has been unregistered
  48325. */
  48326. ActionManager.prototype.unregisterAction = function (action) {
  48327. var index = this.actions.indexOf(action);
  48328. if (index !== -1) {
  48329. this.actions.splice(index, 1);
  48330. ActionManager.Triggers[action.trigger] -= 1;
  48331. if (ActionManager.Triggers[action.trigger] === 0) {
  48332. delete ActionManager.Triggers[action.trigger];
  48333. }
  48334. delete action._actionManager;
  48335. return true;
  48336. }
  48337. return false;
  48338. };
  48339. /**
  48340. * Process a specific trigger
  48341. * @param {number} trigger - the trigger to process
  48342. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48343. */
  48344. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48345. for (var index = 0; index < this.actions.length; index++) {
  48346. var action = this.actions[index];
  48347. if (action.trigger === trigger) {
  48348. if (evt) {
  48349. if (trigger === ActionManager.OnKeyUpTrigger
  48350. || trigger === ActionManager.OnKeyDownTrigger) {
  48351. var parameter = action.getTriggerParameter();
  48352. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48353. if (!parameter.toLowerCase) {
  48354. continue;
  48355. }
  48356. var lowerCase = parameter.toLowerCase();
  48357. if (lowerCase !== evt.sourceEvent.key) {
  48358. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48359. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48360. if (actualkey !== lowerCase) {
  48361. continue;
  48362. }
  48363. }
  48364. }
  48365. }
  48366. }
  48367. action._executeCurrent(evt);
  48368. }
  48369. }
  48370. };
  48371. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48372. var properties = propertyPath.split(".");
  48373. for (var index = 0; index < properties.length - 1; index++) {
  48374. target = target[properties[index]];
  48375. }
  48376. return target;
  48377. };
  48378. ActionManager.prototype._getProperty = function (propertyPath) {
  48379. var properties = propertyPath.split(".");
  48380. return properties[properties.length - 1];
  48381. };
  48382. ActionManager.prototype.serialize = function (name) {
  48383. var root = {
  48384. children: new Array(),
  48385. name: name,
  48386. type: 3,
  48387. properties: new Array() // Empty for root but required
  48388. };
  48389. for (var i = 0; i < this.actions.length; i++) {
  48390. var triggerObject = {
  48391. type: 0,
  48392. children: new Array(),
  48393. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48394. properties: new Array()
  48395. };
  48396. var triggerOptions = this.actions[i].triggerOptions;
  48397. if (triggerOptions && typeof triggerOptions !== "number") {
  48398. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48399. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48400. }
  48401. else {
  48402. var parameter = {};
  48403. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48404. if (triggerOptions.parameter.mesh) {
  48405. parameter._meshId = triggerOptions.parameter.mesh.id;
  48406. }
  48407. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48408. }
  48409. }
  48410. // Serialize child action, recursively
  48411. this.actions[i].serialize(triggerObject);
  48412. // Add serialized trigger
  48413. root.children.push(triggerObject);
  48414. }
  48415. return root;
  48416. };
  48417. ActionManager.Parse = function (parsedActions, object, scene) {
  48418. var actionManager = new ActionManager(scene);
  48419. if (object === null)
  48420. scene.actionManager = actionManager;
  48421. else
  48422. object.actionManager = actionManager;
  48423. // instanciate a new object
  48424. var instanciate = function (name, params) {
  48425. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48426. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48427. newInstance.constructor.apply(newInstance, params);
  48428. return newInstance;
  48429. };
  48430. var parseParameter = function (name, value, target, propertyPath) {
  48431. if (propertyPath === null) {
  48432. // String, boolean or float
  48433. var floatValue = parseFloat(value);
  48434. if (value === "true" || value === "false")
  48435. return value === "true";
  48436. else
  48437. return isNaN(floatValue) ? value : floatValue;
  48438. }
  48439. var effectiveTarget = propertyPath.split(".");
  48440. var values = value.split(",");
  48441. // Get effective Target
  48442. for (var i = 0; i < effectiveTarget.length; i++) {
  48443. target = target[effectiveTarget[i]];
  48444. }
  48445. // Return appropriate value with its type
  48446. if (typeof (target) === "boolean")
  48447. return values[0] === "true";
  48448. if (typeof (target) === "string")
  48449. return values[0];
  48450. // Parameters with multiple values such as Vector3 etc.
  48451. var split = new Array();
  48452. for (var i = 0; i < values.length; i++)
  48453. split.push(parseFloat(values[i]));
  48454. if (target instanceof BABYLON.Vector3)
  48455. return BABYLON.Vector3.FromArray(split);
  48456. if (target instanceof BABYLON.Vector4)
  48457. return BABYLON.Vector4.FromArray(split);
  48458. if (target instanceof BABYLON.Color3)
  48459. return BABYLON.Color3.FromArray(split);
  48460. if (target instanceof BABYLON.Color4)
  48461. return BABYLON.Color4.FromArray(split);
  48462. return parseFloat(values[0]);
  48463. };
  48464. // traverse graph per trigger
  48465. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48466. if (combineArray === void 0) { combineArray = null; }
  48467. if (parsedAction.detached)
  48468. return;
  48469. var parameters = new Array();
  48470. var target = null;
  48471. var propertyPath = null;
  48472. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48473. // Parameters
  48474. if (parsedAction.type === 2)
  48475. parameters.push(actionManager);
  48476. else
  48477. parameters.push(trigger);
  48478. if (combine) {
  48479. var actions = new Array();
  48480. for (var j = 0; j < parsedAction.combine.length; j++) {
  48481. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48482. }
  48483. parameters.push(actions);
  48484. }
  48485. else {
  48486. for (var i = 0; i < parsedAction.properties.length; i++) {
  48487. var value = parsedAction.properties[i].value;
  48488. var name = parsedAction.properties[i].name;
  48489. var targetType = parsedAction.properties[i].targetType;
  48490. if (name === "target")
  48491. if (targetType !== null && targetType === "SceneProperties")
  48492. value = target = scene;
  48493. else
  48494. value = target = scene.getNodeByName(value);
  48495. else if (name === "parent")
  48496. value = scene.getNodeByName(value);
  48497. else if (name === "sound")
  48498. value = scene.getSoundByName(value);
  48499. else if (name !== "propertyPath") {
  48500. if (parsedAction.type === 2 && name === "operator")
  48501. value = BABYLON.ValueCondition[value];
  48502. else
  48503. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48504. }
  48505. else {
  48506. propertyPath = value;
  48507. }
  48508. parameters.push(value);
  48509. }
  48510. }
  48511. if (combineArray === null) {
  48512. parameters.push(condition);
  48513. }
  48514. else {
  48515. parameters.push(null);
  48516. }
  48517. // If interpolate value action
  48518. if (parsedAction.name === "InterpolateValueAction") {
  48519. var param = parameters[parameters.length - 2];
  48520. parameters[parameters.length - 1] = param;
  48521. parameters[parameters.length - 2] = condition;
  48522. }
  48523. // Action or condition(s) and not CombineAction
  48524. var newAction = instanciate(parsedAction.name, parameters);
  48525. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48526. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48527. if (action)
  48528. action.then(nothing);
  48529. else
  48530. actionManager.registerAction(nothing);
  48531. action = nothing;
  48532. }
  48533. if (combineArray === null) {
  48534. if (newAction instanceof BABYLON.Condition) {
  48535. condition = newAction;
  48536. newAction = action;
  48537. }
  48538. else {
  48539. condition = null;
  48540. if (action)
  48541. action.then(newAction);
  48542. else
  48543. actionManager.registerAction(newAction);
  48544. }
  48545. }
  48546. else {
  48547. combineArray.push(newAction);
  48548. }
  48549. for (var i = 0; i < parsedAction.children.length; i++)
  48550. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48551. };
  48552. // triggers
  48553. for (var i = 0; i < parsedActions.children.length; i++) {
  48554. var triggerParams;
  48555. var trigger = parsedActions.children[i];
  48556. if (trigger.properties.length > 0) {
  48557. var param = trigger.properties[0].value;
  48558. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48559. if (value._meshId) {
  48560. value.mesh = scene.getMeshByID(value._meshId);
  48561. }
  48562. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48563. }
  48564. else
  48565. triggerParams = ActionManager[trigger.name];
  48566. for (var j = 0; j < trigger.children.length; j++) {
  48567. if (!trigger.detached)
  48568. traverse(trigger.children[j], triggerParams, null, null);
  48569. }
  48570. }
  48571. };
  48572. ActionManager.GetTriggerName = function (trigger) {
  48573. switch (trigger) {
  48574. case 0: return "NothingTrigger";
  48575. case 1: return "OnPickTrigger";
  48576. case 2: return "OnLeftPickTrigger";
  48577. case 3: return "OnRightPickTrigger";
  48578. case 4: return "OnCenterPickTrigger";
  48579. case 5: return "OnPickDownTrigger";
  48580. case 6: return "OnPickUpTrigger";
  48581. case 7: return "OnLongPressTrigger";
  48582. case 8: return "OnPointerOverTrigger";
  48583. case 9: return "OnPointerOutTrigger";
  48584. case 10: return "OnEveryFrameTrigger";
  48585. case 11: return "OnIntersectionEnterTrigger";
  48586. case 12: return "OnIntersectionExitTrigger";
  48587. case 13: return "OnKeyDownTrigger";
  48588. case 14: return "OnKeyUpTrigger";
  48589. case 15: return "OnPickOutTrigger";
  48590. default: return "";
  48591. }
  48592. };
  48593. // Statics
  48594. ActionManager._NothingTrigger = 0;
  48595. ActionManager._OnPickTrigger = 1;
  48596. ActionManager._OnLeftPickTrigger = 2;
  48597. ActionManager._OnRightPickTrigger = 3;
  48598. ActionManager._OnCenterPickTrigger = 4;
  48599. ActionManager._OnPickDownTrigger = 5;
  48600. ActionManager._OnDoublePickTrigger = 6;
  48601. ActionManager._OnPickUpTrigger = 7;
  48602. ActionManager._OnLongPressTrigger = 8;
  48603. ActionManager._OnPointerOverTrigger = 9;
  48604. ActionManager._OnPointerOutTrigger = 10;
  48605. ActionManager._OnEveryFrameTrigger = 11;
  48606. ActionManager._OnIntersectionEnterTrigger = 12;
  48607. ActionManager._OnIntersectionExitTrigger = 13;
  48608. ActionManager._OnKeyDownTrigger = 14;
  48609. ActionManager._OnKeyUpTrigger = 15;
  48610. ActionManager._OnPickOutTrigger = 16;
  48611. ActionManager.Triggers = {};
  48612. return ActionManager;
  48613. }());
  48614. BABYLON.ActionManager = ActionManager;
  48615. })(BABYLON || (BABYLON = {}));
  48616. //# sourceMappingURL=babylon.actionManager.js.map
  48617. var BABYLON;
  48618. (function (BABYLON) {
  48619. var InterpolateValueAction = /** @class */ (function (_super) {
  48620. __extends(InterpolateValueAction, _super);
  48621. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48622. if (duration === void 0) { duration = 1000; }
  48623. var _this = _super.call(this, triggerOptions, condition) || this;
  48624. _this.propertyPath = propertyPath;
  48625. _this.value = value;
  48626. _this.duration = duration;
  48627. _this.stopOtherAnimations = stopOtherAnimations;
  48628. _this.onInterpolationDone = onInterpolationDone;
  48629. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48630. _this._target = _this._effectiveTarget = target;
  48631. return _this;
  48632. }
  48633. InterpolateValueAction.prototype._prepare = function () {
  48634. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48635. this._property = this._getProperty(this.propertyPath);
  48636. };
  48637. InterpolateValueAction.prototype.execute = function () {
  48638. var _this = this;
  48639. var scene = this._actionManager.getScene();
  48640. var keys = [
  48641. {
  48642. frame: 0,
  48643. value: this._effectiveTarget[this._property]
  48644. }, {
  48645. frame: 100,
  48646. value: this.value
  48647. }
  48648. ];
  48649. var dataType;
  48650. if (typeof this.value === "number") {
  48651. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48652. }
  48653. else if (this.value instanceof BABYLON.Color3) {
  48654. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48655. }
  48656. else if (this.value instanceof BABYLON.Vector3) {
  48657. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48658. }
  48659. else if (this.value instanceof BABYLON.Matrix) {
  48660. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48661. }
  48662. else if (this.value instanceof BABYLON.Quaternion) {
  48663. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48664. }
  48665. else {
  48666. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48667. return;
  48668. }
  48669. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48670. animation.setKeys(keys);
  48671. if (this.stopOtherAnimations) {
  48672. scene.stopAnimation(this._effectiveTarget);
  48673. }
  48674. var wrapper = function () {
  48675. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48676. if (_this.onInterpolationDone) {
  48677. _this.onInterpolationDone();
  48678. }
  48679. };
  48680. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48681. };
  48682. InterpolateValueAction.prototype.serialize = function (parent) {
  48683. return _super.prototype._serialize.call(this, {
  48684. name: "InterpolateValueAction",
  48685. properties: [
  48686. BABYLON.Action._GetTargetProperty(this._target),
  48687. { name: "propertyPath", value: this.propertyPath },
  48688. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48689. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48690. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48691. ]
  48692. }, parent);
  48693. };
  48694. return InterpolateValueAction;
  48695. }(BABYLON.Action));
  48696. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48697. })(BABYLON || (BABYLON = {}));
  48698. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48699. var BABYLON;
  48700. (function (BABYLON) {
  48701. var SwitchBooleanAction = /** @class */ (function (_super) {
  48702. __extends(SwitchBooleanAction, _super);
  48703. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48704. var _this = _super.call(this, triggerOptions, condition) || this;
  48705. _this.propertyPath = propertyPath;
  48706. _this._target = _this._effectiveTarget = target;
  48707. return _this;
  48708. }
  48709. SwitchBooleanAction.prototype._prepare = function () {
  48710. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48711. this._property = this._getProperty(this.propertyPath);
  48712. };
  48713. SwitchBooleanAction.prototype.execute = function () {
  48714. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48715. };
  48716. SwitchBooleanAction.prototype.serialize = function (parent) {
  48717. return _super.prototype._serialize.call(this, {
  48718. name: "SwitchBooleanAction",
  48719. properties: [
  48720. BABYLON.Action._GetTargetProperty(this._target),
  48721. { name: "propertyPath", value: this.propertyPath }
  48722. ]
  48723. }, parent);
  48724. };
  48725. return SwitchBooleanAction;
  48726. }(BABYLON.Action));
  48727. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48728. var SetStateAction = /** @class */ (function (_super) {
  48729. __extends(SetStateAction, _super);
  48730. function SetStateAction(triggerOptions, target, value, condition) {
  48731. var _this = _super.call(this, triggerOptions, condition) || this;
  48732. _this.value = value;
  48733. _this._target = target;
  48734. return _this;
  48735. }
  48736. SetStateAction.prototype.execute = function () {
  48737. this._target.state = this.value;
  48738. };
  48739. SetStateAction.prototype.serialize = function (parent) {
  48740. return _super.prototype._serialize.call(this, {
  48741. name: "SetStateAction",
  48742. properties: [
  48743. BABYLON.Action._GetTargetProperty(this._target),
  48744. { name: "value", value: this.value }
  48745. ]
  48746. }, parent);
  48747. };
  48748. return SetStateAction;
  48749. }(BABYLON.Action));
  48750. BABYLON.SetStateAction = SetStateAction;
  48751. var SetValueAction = /** @class */ (function (_super) {
  48752. __extends(SetValueAction, _super);
  48753. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48754. var _this = _super.call(this, triggerOptions, condition) || this;
  48755. _this.propertyPath = propertyPath;
  48756. _this.value = value;
  48757. _this._target = _this._effectiveTarget = target;
  48758. return _this;
  48759. }
  48760. SetValueAction.prototype._prepare = function () {
  48761. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48762. this._property = this._getProperty(this.propertyPath);
  48763. };
  48764. SetValueAction.prototype.execute = function () {
  48765. this._effectiveTarget[this._property] = this.value;
  48766. if (this._target.markAsDirty) {
  48767. this._target.markAsDirty(this._property);
  48768. }
  48769. };
  48770. SetValueAction.prototype.serialize = function (parent) {
  48771. return _super.prototype._serialize.call(this, {
  48772. name: "SetValueAction",
  48773. properties: [
  48774. BABYLON.Action._GetTargetProperty(this._target),
  48775. { name: "propertyPath", value: this.propertyPath },
  48776. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48777. ]
  48778. }, parent);
  48779. };
  48780. return SetValueAction;
  48781. }(BABYLON.Action));
  48782. BABYLON.SetValueAction = SetValueAction;
  48783. var IncrementValueAction = /** @class */ (function (_super) {
  48784. __extends(IncrementValueAction, _super);
  48785. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48786. var _this = _super.call(this, triggerOptions, condition) || this;
  48787. _this.propertyPath = propertyPath;
  48788. _this.value = value;
  48789. _this._target = _this._effectiveTarget = target;
  48790. return _this;
  48791. }
  48792. IncrementValueAction.prototype._prepare = function () {
  48793. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48794. this._property = this._getProperty(this.propertyPath);
  48795. if (typeof this._effectiveTarget[this._property] !== "number") {
  48796. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48797. }
  48798. };
  48799. IncrementValueAction.prototype.execute = function () {
  48800. this._effectiveTarget[this._property] += this.value;
  48801. if (this._target.markAsDirty) {
  48802. this._target.markAsDirty(this._property);
  48803. }
  48804. };
  48805. IncrementValueAction.prototype.serialize = function (parent) {
  48806. return _super.prototype._serialize.call(this, {
  48807. name: "IncrementValueAction",
  48808. properties: [
  48809. BABYLON.Action._GetTargetProperty(this._target),
  48810. { name: "propertyPath", value: this.propertyPath },
  48811. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48812. ]
  48813. }, parent);
  48814. };
  48815. return IncrementValueAction;
  48816. }(BABYLON.Action));
  48817. BABYLON.IncrementValueAction = IncrementValueAction;
  48818. var PlayAnimationAction = /** @class */ (function (_super) {
  48819. __extends(PlayAnimationAction, _super);
  48820. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48821. var _this = _super.call(this, triggerOptions, condition) || this;
  48822. _this.from = from;
  48823. _this.to = to;
  48824. _this.loop = loop;
  48825. _this._target = target;
  48826. return _this;
  48827. }
  48828. PlayAnimationAction.prototype._prepare = function () {
  48829. };
  48830. PlayAnimationAction.prototype.execute = function () {
  48831. var scene = this._actionManager.getScene();
  48832. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48833. };
  48834. PlayAnimationAction.prototype.serialize = function (parent) {
  48835. return _super.prototype._serialize.call(this, {
  48836. name: "PlayAnimationAction",
  48837. properties: [
  48838. BABYLON.Action._GetTargetProperty(this._target),
  48839. { name: "from", value: String(this.from) },
  48840. { name: "to", value: String(this.to) },
  48841. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48842. ]
  48843. }, parent);
  48844. };
  48845. return PlayAnimationAction;
  48846. }(BABYLON.Action));
  48847. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48848. var StopAnimationAction = /** @class */ (function (_super) {
  48849. __extends(StopAnimationAction, _super);
  48850. function StopAnimationAction(triggerOptions, target, condition) {
  48851. var _this = _super.call(this, triggerOptions, condition) || this;
  48852. _this._target = target;
  48853. return _this;
  48854. }
  48855. StopAnimationAction.prototype._prepare = function () {
  48856. };
  48857. StopAnimationAction.prototype.execute = function () {
  48858. var scene = this._actionManager.getScene();
  48859. scene.stopAnimation(this._target);
  48860. };
  48861. StopAnimationAction.prototype.serialize = function (parent) {
  48862. return _super.prototype._serialize.call(this, {
  48863. name: "StopAnimationAction",
  48864. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48865. }, parent);
  48866. };
  48867. return StopAnimationAction;
  48868. }(BABYLON.Action));
  48869. BABYLON.StopAnimationAction = StopAnimationAction;
  48870. var DoNothingAction = /** @class */ (function (_super) {
  48871. __extends(DoNothingAction, _super);
  48872. function DoNothingAction(triggerOptions, condition) {
  48873. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48874. return _super.call(this, triggerOptions, condition) || this;
  48875. }
  48876. DoNothingAction.prototype.execute = function () {
  48877. };
  48878. DoNothingAction.prototype.serialize = function (parent) {
  48879. return _super.prototype._serialize.call(this, {
  48880. name: "DoNothingAction",
  48881. properties: []
  48882. }, parent);
  48883. };
  48884. return DoNothingAction;
  48885. }(BABYLON.Action));
  48886. BABYLON.DoNothingAction = DoNothingAction;
  48887. var CombineAction = /** @class */ (function (_super) {
  48888. __extends(CombineAction, _super);
  48889. function CombineAction(triggerOptions, children, condition) {
  48890. var _this = _super.call(this, triggerOptions, condition) || this;
  48891. _this.children = children;
  48892. return _this;
  48893. }
  48894. CombineAction.prototype._prepare = function () {
  48895. for (var index = 0; index < this.children.length; index++) {
  48896. this.children[index]._actionManager = this._actionManager;
  48897. this.children[index]._prepare();
  48898. }
  48899. };
  48900. CombineAction.prototype.execute = function (evt) {
  48901. for (var index = 0; index < this.children.length; index++) {
  48902. this.children[index].execute(evt);
  48903. }
  48904. };
  48905. CombineAction.prototype.serialize = function (parent) {
  48906. var serializationObject = _super.prototype._serialize.call(this, {
  48907. name: "CombineAction",
  48908. properties: [],
  48909. combine: []
  48910. }, parent);
  48911. for (var i = 0; i < this.children.length; i++) {
  48912. serializationObject.combine.push(this.children[i].serialize(null));
  48913. }
  48914. return serializationObject;
  48915. };
  48916. return CombineAction;
  48917. }(BABYLON.Action));
  48918. BABYLON.CombineAction = CombineAction;
  48919. var ExecuteCodeAction = /** @class */ (function (_super) {
  48920. __extends(ExecuteCodeAction, _super);
  48921. function ExecuteCodeAction(triggerOptions, func, condition) {
  48922. var _this = _super.call(this, triggerOptions, condition) || this;
  48923. _this.func = func;
  48924. return _this;
  48925. }
  48926. ExecuteCodeAction.prototype.execute = function (evt) {
  48927. this.func(evt);
  48928. };
  48929. return ExecuteCodeAction;
  48930. }(BABYLON.Action));
  48931. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48932. var SetParentAction = /** @class */ (function (_super) {
  48933. __extends(SetParentAction, _super);
  48934. function SetParentAction(triggerOptions, target, parent, condition) {
  48935. var _this = _super.call(this, triggerOptions, condition) || this;
  48936. _this._target = target;
  48937. _this._parent = parent;
  48938. return _this;
  48939. }
  48940. SetParentAction.prototype._prepare = function () {
  48941. };
  48942. SetParentAction.prototype.execute = function () {
  48943. if (this._target.parent === this._parent) {
  48944. return;
  48945. }
  48946. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48947. invertParentWorldMatrix.invert();
  48948. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48949. this._target.parent = this._parent;
  48950. };
  48951. SetParentAction.prototype.serialize = function (parent) {
  48952. return _super.prototype._serialize.call(this, {
  48953. name: "SetParentAction",
  48954. properties: [
  48955. BABYLON.Action._GetTargetProperty(this._target),
  48956. BABYLON.Action._GetTargetProperty(this._parent),
  48957. ]
  48958. }, parent);
  48959. };
  48960. return SetParentAction;
  48961. }(BABYLON.Action));
  48962. BABYLON.SetParentAction = SetParentAction;
  48963. var PlaySoundAction = /** @class */ (function (_super) {
  48964. __extends(PlaySoundAction, _super);
  48965. function PlaySoundAction(triggerOptions, sound, condition) {
  48966. var _this = _super.call(this, triggerOptions, condition) || this;
  48967. _this._sound = sound;
  48968. return _this;
  48969. }
  48970. PlaySoundAction.prototype._prepare = function () {
  48971. };
  48972. PlaySoundAction.prototype.execute = function () {
  48973. if (this._sound !== undefined)
  48974. this._sound.play();
  48975. };
  48976. PlaySoundAction.prototype.serialize = function (parent) {
  48977. return _super.prototype._serialize.call(this, {
  48978. name: "PlaySoundAction",
  48979. properties: [{ name: "sound", value: this._sound.name }]
  48980. }, parent);
  48981. };
  48982. return PlaySoundAction;
  48983. }(BABYLON.Action));
  48984. BABYLON.PlaySoundAction = PlaySoundAction;
  48985. var StopSoundAction = /** @class */ (function (_super) {
  48986. __extends(StopSoundAction, _super);
  48987. function StopSoundAction(triggerOptions, sound, condition) {
  48988. var _this = _super.call(this, triggerOptions, condition) || this;
  48989. _this._sound = sound;
  48990. return _this;
  48991. }
  48992. StopSoundAction.prototype._prepare = function () {
  48993. };
  48994. StopSoundAction.prototype.execute = function () {
  48995. if (this._sound !== undefined)
  48996. this._sound.stop();
  48997. };
  48998. StopSoundAction.prototype.serialize = function (parent) {
  48999. return _super.prototype._serialize.call(this, {
  49000. name: "StopSoundAction",
  49001. properties: [{ name: "sound", value: this._sound.name }]
  49002. }, parent);
  49003. };
  49004. return StopSoundAction;
  49005. }(BABYLON.Action));
  49006. BABYLON.StopSoundAction = StopSoundAction;
  49007. })(BABYLON || (BABYLON = {}));
  49008. //# sourceMappingURL=babylon.directActions.js.map
  49009. var BABYLON;
  49010. (function (BABYLON) {
  49011. var SpriteManager = /** @class */ (function () {
  49012. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49013. if (epsilon === void 0) { epsilon = 0.01; }
  49014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49015. this.name = name;
  49016. this.sprites = new Array();
  49017. this.renderingGroupId = 0;
  49018. this.layerMask = 0x0FFFFFFF;
  49019. this.fogEnabled = true;
  49020. this.isPickable = false;
  49021. /**
  49022. * An event triggered when the manager is disposed.
  49023. * @type {BABYLON.Observable}
  49024. */
  49025. this.onDisposeObservable = new BABYLON.Observable();
  49026. this._vertexBuffers = {};
  49027. this._capacity = capacity;
  49028. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49029. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49030. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49031. if (cellSize.width && cellSize.height) {
  49032. this.cellWidth = cellSize.width;
  49033. this.cellHeight = cellSize.height;
  49034. }
  49035. else if (cellSize !== undefined) {
  49036. this.cellWidth = cellSize;
  49037. this.cellHeight = cellSize;
  49038. }
  49039. else {
  49040. return;
  49041. }
  49042. this._epsilon = epsilon;
  49043. this._scene = scene;
  49044. this._scene.spriteManagers.push(this);
  49045. var indices = [];
  49046. var index = 0;
  49047. for (var count = 0; count < capacity; count++) {
  49048. indices.push(index);
  49049. indices.push(index + 1);
  49050. indices.push(index + 2);
  49051. indices.push(index);
  49052. indices.push(index + 2);
  49053. indices.push(index + 3);
  49054. index += 4;
  49055. }
  49056. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49057. // VBO
  49058. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49059. this._vertexData = new Float32Array(capacity * 16 * 4);
  49060. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49061. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49062. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49063. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49064. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49066. this._vertexBuffers["options"] = options;
  49067. this._vertexBuffers["cellInfo"] = cellInfo;
  49068. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49069. // Effects
  49070. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49071. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49072. }
  49073. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49074. set: function (callback) {
  49075. if (this._onDisposeObserver) {
  49076. this.onDisposeObservable.remove(this._onDisposeObserver);
  49077. }
  49078. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49079. },
  49080. enumerable: true,
  49081. configurable: true
  49082. });
  49083. Object.defineProperty(SpriteManager.prototype, "texture", {
  49084. get: function () {
  49085. return this._spriteTexture;
  49086. },
  49087. set: function (value) {
  49088. this._spriteTexture = value;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49094. var arrayOffset = index * 16;
  49095. if (offsetX === 0)
  49096. offsetX = this._epsilon;
  49097. else if (offsetX === 1)
  49098. offsetX = 1 - this._epsilon;
  49099. if (offsetY === 0)
  49100. offsetY = this._epsilon;
  49101. else if (offsetY === 1)
  49102. offsetY = 1 - this._epsilon;
  49103. this._vertexData[arrayOffset] = sprite.position.x;
  49104. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49105. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49106. this._vertexData[arrayOffset + 3] = sprite.angle;
  49107. this._vertexData[arrayOffset + 4] = sprite.width;
  49108. this._vertexData[arrayOffset + 5] = sprite.height;
  49109. this._vertexData[arrayOffset + 6] = offsetX;
  49110. this._vertexData[arrayOffset + 7] = offsetY;
  49111. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49112. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49113. var offset = (sprite.cellIndex / rowSize) >> 0;
  49114. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49115. this._vertexData[arrayOffset + 11] = offset;
  49116. // Color
  49117. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49118. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49119. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49120. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49121. };
  49122. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49123. var count = Math.min(this._capacity, this.sprites.length);
  49124. var min = BABYLON.Vector3.Zero();
  49125. var max = BABYLON.Vector3.Zero();
  49126. var distance = Number.MAX_VALUE;
  49127. var currentSprite = null;
  49128. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49129. var cameraView = camera.getViewMatrix();
  49130. for (var index = 0; index < count; index++) {
  49131. var sprite = this.sprites[index];
  49132. if (!sprite) {
  49133. continue;
  49134. }
  49135. if (predicate) {
  49136. if (!predicate(sprite)) {
  49137. continue;
  49138. }
  49139. }
  49140. else if (!sprite.isPickable) {
  49141. continue;
  49142. }
  49143. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49144. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49145. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49146. if (ray.intersectsBoxMinMax(min, max)) {
  49147. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49148. if (distance > currentDistance) {
  49149. distance = currentDistance;
  49150. currentSprite = sprite;
  49151. if (fastCheck) {
  49152. break;
  49153. }
  49154. }
  49155. }
  49156. }
  49157. if (currentSprite) {
  49158. var result = new BABYLON.PickingInfo();
  49159. result.hit = true;
  49160. result.pickedSprite = currentSprite;
  49161. result.distance = distance;
  49162. return result;
  49163. }
  49164. return null;
  49165. };
  49166. SpriteManager.prototype.render = function () {
  49167. // Check
  49168. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49169. return;
  49170. var engine = this._scene.getEngine();
  49171. var baseSize = this._spriteTexture.getBaseSize();
  49172. // Sprites
  49173. var deltaTime = engine.getDeltaTime();
  49174. var max = Math.min(this._capacity, this.sprites.length);
  49175. var rowSize = baseSize.width / this.cellWidth;
  49176. var offset = 0;
  49177. for (var index = 0; index < max; index++) {
  49178. var sprite = this.sprites[index];
  49179. if (!sprite) {
  49180. continue;
  49181. }
  49182. sprite._animate(deltaTime);
  49183. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49184. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49185. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49186. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49187. }
  49188. this._buffer.update(this._vertexData);
  49189. // Render
  49190. var effect = this._effectBase;
  49191. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49192. effect = this._effectFog;
  49193. }
  49194. engine.enableEffect(effect);
  49195. var viewMatrix = this._scene.getViewMatrix();
  49196. effect.setTexture("diffuseSampler", this._spriteTexture);
  49197. effect.setMatrix("view", viewMatrix);
  49198. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49199. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49200. // Fog
  49201. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49202. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49203. effect.setColor3("vFogColor", this._scene.fogColor);
  49204. }
  49205. // VBOs
  49206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49207. // Draw order
  49208. engine.setDepthFunctionToLessOrEqual();
  49209. effect.setBool("alphaTest", true);
  49210. engine.setColorWrite(false);
  49211. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49212. engine.setColorWrite(true);
  49213. effect.setBool("alphaTest", false);
  49214. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49215. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49217. };
  49218. SpriteManager.prototype.dispose = function () {
  49219. if (this._buffer) {
  49220. this._buffer.dispose();
  49221. this._buffer = null;
  49222. }
  49223. if (this._indexBuffer) {
  49224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49225. this._indexBuffer = null;
  49226. }
  49227. if (this._spriteTexture) {
  49228. this._spriteTexture.dispose();
  49229. this._spriteTexture = null;
  49230. }
  49231. // Remove from scene
  49232. var index = this._scene.spriteManagers.indexOf(this);
  49233. this._scene.spriteManagers.splice(index, 1);
  49234. // Callback
  49235. this.onDisposeObservable.notifyObservers(this);
  49236. this.onDisposeObservable.clear();
  49237. };
  49238. return SpriteManager;
  49239. }());
  49240. BABYLON.SpriteManager = SpriteManager;
  49241. })(BABYLON || (BABYLON = {}));
  49242. //# sourceMappingURL=babylon.spriteManager.js.map
  49243. var BABYLON;
  49244. (function (BABYLON) {
  49245. var Sprite = /** @class */ (function () {
  49246. function Sprite(name, manager) {
  49247. this.name = name;
  49248. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49249. this.width = 1.0;
  49250. this.height = 1.0;
  49251. this.angle = 0;
  49252. this.cellIndex = 0;
  49253. this.invertU = 0;
  49254. this.invertV = 0;
  49255. this.animations = new Array();
  49256. this.isPickable = false;
  49257. this._animationStarted = false;
  49258. this._loopAnimation = false;
  49259. this._fromIndex = 0;
  49260. this._toIndex = 0;
  49261. this._delay = 0;
  49262. this._direction = 1;
  49263. this._time = 0;
  49264. this._manager = manager;
  49265. this._manager.sprites.push(this);
  49266. this.position = BABYLON.Vector3.Zero();
  49267. }
  49268. Object.defineProperty(Sprite.prototype, "size", {
  49269. get: function () {
  49270. return this.width;
  49271. },
  49272. set: function (value) {
  49273. this.width = value;
  49274. this.height = value;
  49275. },
  49276. enumerable: true,
  49277. configurable: true
  49278. });
  49279. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49280. this._fromIndex = from;
  49281. this._toIndex = to;
  49282. this._loopAnimation = loop;
  49283. this._delay = delay;
  49284. this._animationStarted = true;
  49285. this._direction = from < to ? 1 : -1;
  49286. this.cellIndex = from;
  49287. this._time = 0;
  49288. this._onAnimationEnd = onAnimationEnd;
  49289. };
  49290. Sprite.prototype.stopAnimation = function () {
  49291. this._animationStarted = false;
  49292. };
  49293. Sprite.prototype._animate = function (deltaTime) {
  49294. if (!this._animationStarted)
  49295. return;
  49296. this._time += deltaTime;
  49297. if (this._time > this._delay) {
  49298. this._time = this._time % this._delay;
  49299. this.cellIndex += this._direction;
  49300. if (this.cellIndex > this._toIndex) {
  49301. if (this._loopAnimation) {
  49302. this.cellIndex = this._fromIndex;
  49303. }
  49304. else {
  49305. this.cellIndex = this._toIndex;
  49306. this._animationStarted = false;
  49307. if (this._onAnimationEnd) {
  49308. this._onAnimationEnd();
  49309. }
  49310. if (this.disposeWhenFinishedAnimating) {
  49311. this.dispose();
  49312. }
  49313. }
  49314. }
  49315. }
  49316. };
  49317. Sprite.prototype.dispose = function () {
  49318. for (var i = 0; i < this._manager.sprites.length; i++) {
  49319. if (this._manager.sprites[i] == this) {
  49320. this._manager.sprites.splice(i, 1);
  49321. }
  49322. }
  49323. };
  49324. return Sprite;
  49325. }());
  49326. BABYLON.Sprite = Sprite;
  49327. })(BABYLON || (BABYLON = {}));
  49328. //# sourceMappingURL=babylon.sprite.js.map
  49329. var BABYLON;
  49330. (function (BABYLON) {
  49331. var IntersectionInfo = /** @class */ (function () {
  49332. function IntersectionInfo(bu, bv, distance) {
  49333. this.bu = bu;
  49334. this.bv = bv;
  49335. this.distance = distance;
  49336. this.faceId = 0;
  49337. this.subMeshId = 0;
  49338. }
  49339. return IntersectionInfo;
  49340. }());
  49341. BABYLON.IntersectionInfo = IntersectionInfo;
  49342. var PickingInfo = /** @class */ (function () {
  49343. function PickingInfo() {
  49344. this.hit = false;
  49345. this.distance = 0;
  49346. this.pickedPoint = null;
  49347. this.pickedMesh = null;
  49348. this.bu = 0;
  49349. this.bv = 0;
  49350. this.faceId = -1;
  49351. this.subMeshId = 0;
  49352. this.pickedSprite = null;
  49353. }
  49354. // Methods
  49355. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49356. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49357. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49358. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49359. return null;
  49360. }
  49361. var indices = this.pickedMesh.getIndices();
  49362. if (!indices) {
  49363. return null;
  49364. }
  49365. var result;
  49366. if (useVerticesNormals) {
  49367. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49368. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49369. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49370. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49371. normal0 = normal0.scale(this.bu);
  49372. normal1 = normal1.scale(this.bv);
  49373. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49374. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49375. }
  49376. else {
  49377. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49378. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49379. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49380. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49381. var p1p2 = vertex1.subtract(vertex2);
  49382. var p3p2 = vertex3.subtract(vertex2);
  49383. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49384. }
  49385. if (useWorldCoordinates) {
  49386. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49387. }
  49388. return BABYLON.Vector3.Normalize(result);
  49389. };
  49390. PickingInfo.prototype.getTextureCoordinates = function () {
  49391. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49392. return null;
  49393. }
  49394. var indices = this.pickedMesh.getIndices();
  49395. if (!indices) {
  49396. return null;
  49397. }
  49398. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49399. if (!uvs) {
  49400. return null;
  49401. }
  49402. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49403. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49404. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49405. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49406. uv1 = uv1.scale(this.bu);
  49407. uv2 = uv2.scale(this.bv);
  49408. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49409. };
  49410. return PickingInfo;
  49411. }());
  49412. BABYLON.PickingInfo = PickingInfo;
  49413. })(BABYLON || (BABYLON = {}));
  49414. //# sourceMappingURL=babylon.pickingInfo.js.map
  49415. var BABYLON;
  49416. (function (BABYLON) {
  49417. var Ray = /** @class */ (function () {
  49418. function Ray(origin, direction, length) {
  49419. if (length === void 0) { length = Number.MAX_VALUE; }
  49420. this.origin = origin;
  49421. this.direction = direction;
  49422. this.length = length;
  49423. }
  49424. // Methods
  49425. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49426. var d = 0.0;
  49427. var maxValue = Number.MAX_VALUE;
  49428. var inv;
  49429. var min;
  49430. var max;
  49431. var temp;
  49432. if (Math.abs(this.direction.x) < 0.0000001) {
  49433. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49434. return false;
  49435. }
  49436. }
  49437. else {
  49438. inv = 1.0 / this.direction.x;
  49439. min = (minimum.x - this.origin.x) * inv;
  49440. max = (maximum.x - this.origin.x) * inv;
  49441. if (max === -Infinity) {
  49442. max = Infinity;
  49443. }
  49444. if (min > max) {
  49445. temp = min;
  49446. min = max;
  49447. max = temp;
  49448. }
  49449. d = Math.max(min, d);
  49450. maxValue = Math.min(max, maxValue);
  49451. if (d > maxValue) {
  49452. return false;
  49453. }
  49454. }
  49455. if (Math.abs(this.direction.y) < 0.0000001) {
  49456. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49457. return false;
  49458. }
  49459. }
  49460. else {
  49461. inv = 1.0 / this.direction.y;
  49462. min = (minimum.y - this.origin.y) * inv;
  49463. max = (maximum.y - this.origin.y) * inv;
  49464. if (max === -Infinity) {
  49465. max = Infinity;
  49466. }
  49467. if (min > max) {
  49468. temp = min;
  49469. min = max;
  49470. max = temp;
  49471. }
  49472. d = Math.max(min, d);
  49473. maxValue = Math.min(max, maxValue);
  49474. if (d > maxValue) {
  49475. return false;
  49476. }
  49477. }
  49478. if (Math.abs(this.direction.z) < 0.0000001) {
  49479. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49480. return false;
  49481. }
  49482. }
  49483. else {
  49484. inv = 1.0 / this.direction.z;
  49485. min = (minimum.z - this.origin.z) * inv;
  49486. max = (maximum.z - this.origin.z) * inv;
  49487. if (max === -Infinity) {
  49488. max = Infinity;
  49489. }
  49490. if (min > max) {
  49491. temp = min;
  49492. min = max;
  49493. max = temp;
  49494. }
  49495. d = Math.max(min, d);
  49496. maxValue = Math.min(max, maxValue);
  49497. if (d > maxValue) {
  49498. return false;
  49499. }
  49500. }
  49501. return true;
  49502. };
  49503. Ray.prototype.intersectsBox = function (box) {
  49504. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49505. };
  49506. Ray.prototype.intersectsSphere = function (sphere) {
  49507. var x = sphere.center.x - this.origin.x;
  49508. var y = sphere.center.y - this.origin.y;
  49509. var z = sphere.center.z - this.origin.z;
  49510. var pyth = (x * x) + (y * y) + (z * z);
  49511. var rr = sphere.radius * sphere.radius;
  49512. if (pyth <= rr) {
  49513. return true;
  49514. }
  49515. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49516. if (dot < 0.0) {
  49517. return false;
  49518. }
  49519. var temp = pyth - (dot * dot);
  49520. return temp <= rr;
  49521. };
  49522. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49523. if (!this._edge1) {
  49524. this._edge1 = BABYLON.Vector3.Zero();
  49525. this._edge2 = BABYLON.Vector3.Zero();
  49526. this._pvec = BABYLON.Vector3.Zero();
  49527. this._tvec = BABYLON.Vector3.Zero();
  49528. this._qvec = BABYLON.Vector3.Zero();
  49529. }
  49530. vertex1.subtractToRef(vertex0, this._edge1);
  49531. vertex2.subtractToRef(vertex0, this._edge2);
  49532. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49533. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49534. if (det === 0) {
  49535. return null;
  49536. }
  49537. var invdet = 1 / det;
  49538. this.origin.subtractToRef(vertex0, this._tvec);
  49539. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49540. if (bu < 0 || bu > 1.0) {
  49541. return null;
  49542. }
  49543. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49544. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49545. if (bv < 0 || bu + bv > 1.0) {
  49546. return null;
  49547. }
  49548. //check if the distance is longer than the predefined length.
  49549. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49550. if (distance > this.length) {
  49551. return null;
  49552. }
  49553. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49554. };
  49555. Ray.prototype.intersectsPlane = function (plane) {
  49556. var distance;
  49557. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49558. if (Math.abs(result1) < 9.99999997475243E-07) {
  49559. return null;
  49560. }
  49561. else {
  49562. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49563. distance = (-plane.d - result2) / result1;
  49564. if (distance < 0.0) {
  49565. if (distance < -9.99999997475243E-07) {
  49566. return null;
  49567. }
  49568. else {
  49569. return 0;
  49570. }
  49571. }
  49572. return distance;
  49573. }
  49574. };
  49575. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49576. var tm = BABYLON.Tmp.Matrix[0];
  49577. mesh.getWorldMatrix().invertToRef(tm);
  49578. if (this._tmpRay) {
  49579. Ray.TransformToRef(this, tm, this._tmpRay);
  49580. }
  49581. else {
  49582. this._tmpRay = Ray.Transform(this, tm);
  49583. }
  49584. return mesh.intersects(this._tmpRay, fastCheck);
  49585. };
  49586. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49587. if (results) {
  49588. results.length = 0;
  49589. }
  49590. else {
  49591. results = [];
  49592. }
  49593. for (var i = 0; i < meshes.length; i++) {
  49594. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49595. if (pickInfo.hit) {
  49596. results.push(pickInfo);
  49597. }
  49598. }
  49599. results.sort(this._comparePickingInfo);
  49600. return results;
  49601. };
  49602. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49603. if (pickingInfoA.distance < pickingInfoB.distance) {
  49604. return -1;
  49605. }
  49606. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49607. return 1;
  49608. }
  49609. else {
  49610. return 0;
  49611. }
  49612. };
  49613. /**
  49614. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49615. * @param sega the first point of the segment to test the intersection against
  49616. * @param segb the second point of the segment to test the intersection against
  49617. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49618. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49619. */
  49620. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49621. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49622. var u = segb.subtract(sega);
  49623. var v = rsegb.subtract(this.origin);
  49624. var w = sega.subtract(this.origin);
  49625. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49626. var b = BABYLON.Vector3.Dot(u, v);
  49627. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49628. var d = BABYLON.Vector3.Dot(u, w);
  49629. var e = BABYLON.Vector3.Dot(v, w);
  49630. var D = a * c - b * b; // always >= 0
  49631. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49632. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49633. // compute the line parameters of the two closest points
  49634. if (D < Ray.smallnum) {
  49635. sN = 0.0; // force using point P0 on segment S1
  49636. sD = 1.0; // to prevent possible division by 0.0 later
  49637. tN = e;
  49638. tD = c;
  49639. }
  49640. else {
  49641. sN = (b * e - c * d);
  49642. tN = (a * e - b * d);
  49643. if (sN < 0.0) {
  49644. sN = 0.0;
  49645. tN = e;
  49646. tD = c;
  49647. }
  49648. else if (sN > sD) {
  49649. sN = sD;
  49650. tN = e + b;
  49651. tD = c;
  49652. }
  49653. }
  49654. if (tN < 0.0) {
  49655. tN = 0.0;
  49656. // recompute sc for this edge
  49657. if (-d < 0.0) {
  49658. sN = 0.0;
  49659. }
  49660. else if (-d > a)
  49661. sN = sD;
  49662. else {
  49663. sN = -d;
  49664. sD = a;
  49665. }
  49666. }
  49667. else if (tN > tD) {
  49668. tN = tD;
  49669. // recompute sc for this edge
  49670. if ((-d + b) < 0.0) {
  49671. sN = 0;
  49672. }
  49673. else if ((-d + b) > a) {
  49674. sN = sD;
  49675. }
  49676. else {
  49677. sN = (-d + b);
  49678. sD = a;
  49679. }
  49680. }
  49681. // finally do the division to get sc and tc
  49682. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49683. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49684. // get the difference of the two closest points
  49685. var qtc = v.multiplyByFloats(tc, tc, tc);
  49686. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49687. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49688. if (isIntersected) {
  49689. return qtc.length();
  49690. }
  49691. return -1;
  49692. };
  49693. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49694. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49695. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49696. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49697. this.direction.normalize();
  49698. return this;
  49699. };
  49700. // Statics
  49701. Ray.Zero = function () {
  49702. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49703. };
  49704. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49705. var result = Ray.Zero();
  49706. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49707. };
  49708. /**
  49709. * 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
  49710. * transformed to the given world matrix.
  49711. * @param origin The origin point
  49712. * @param end The end point
  49713. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49714. */
  49715. Ray.CreateNewFromTo = function (origin, end, world) {
  49716. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49717. var direction = end.subtract(origin);
  49718. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49719. direction.normalize();
  49720. return Ray.Transform(new Ray(origin, direction, length), world);
  49721. };
  49722. Ray.Transform = function (ray, matrix) {
  49723. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49724. Ray.TransformToRef(ray, matrix, result);
  49725. return result;
  49726. };
  49727. Ray.TransformToRef = function (ray, matrix, result) {
  49728. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49729. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49730. result.length = ray.length;
  49731. var dir = result.direction;
  49732. var len = dir.length();
  49733. if (!(len === 0 || len === 1)) {
  49734. var num = 1.0 / len;
  49735. dir.x *= num;
  49736. dir.y *= num;
  49737. dir.z *= num;
  49738. result.length *= len;
  49739. }
  49740. };
  49741. Ray.smallnum = 0.00000001;
  49742. Ray.rayl = 10e8;
  49743. return Ray;
  49744. }());
  49745. BABYLON.Ray = Ray;
  49746. })(BABYLON || (BABYLON = {}));
  49747. //# sourceMappingURL=babylon.ray.js.map
  49748. var BABYLON;
  49749. (function (BABYLON) {
  49750. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49751. if (boxMin.x > sphereCenter.x + sphereRadius)
  49752. return false;
  49753. if (sphereCenter.x - sphereRadius > boxMax.x)
  49754. return false;
  49755. if (boxMin.y > sphereCenter.y + sphereRadius)
  49756. return false;
  49757. if (sphereCenter.y - sphereRadius > boxMax.y)
  49758. return false;
  49759. if (boxMin.z > sphereCenter.z + sphereRadius)
  49760. return false;
  49761. if (sphereCenter.z - sphereRadius > boxMax.z)
  49762. return false;
  49763. return true;
  49764. };
  49765. var getLowestRoot = (function () {
  49766. var result = { root: 0, found: false };
  49767. return function (a, b, c, maxR) {
  49768. result.root = 0;
  49769. result.found = false;
  49770. var determinant = b * b - 4.0 * a * c;
  49771. if (determinant < 0)
  49772. return result;
  49773. var sqrtD = Math.sqrt(determinant);
  49774. var r1 = (-b - sqrtD) / (2.0 * a);
  49775. var r2 = (-b + sqrtD) / (2.0 * a);
  49776. if (r1 > r2) {
  49777. var temp = r2;
  49778. r2 = r1;
  49779. r1 = temp;
  49780. }
  49781. if (r1 > 0 && r1 < maxR) {
  49782. result.root = r1;
  49783. result.found = true;
  49784. return result;
  49785. }
  49786. if (r2 > 0 && r2 < maxR) {
  49787. result.root = r2;
  49788. result.found = true;
  49789. return result;
  49790. }
  49791. return result;
  49792. };
  49793. })();
  49794. var Collider = /** @class */ (function () {
  49795. function Collider() {
  49796. this._collisionPoint = BABYLON.Vector3.Zero();
  49797. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49798. this._tempVector = BABYLON.Vector3.Zero();
  49799. this._tempVector2 = BABYLON.Vector3.Zero();
  49800. this._tempVector3 = BABYLON.Vector3.Zero();
  49801. this._tempVector4 = BABYLON.Vector3.Zero();
  49802. this._edge = BABYLON.Vector3.Zero();
  49803. this._baseToVertex = BABYLON.Vector3.Zero();
  49804. this._destinationPoint = BABYLON.Vector3.Zero();
  49805. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49806. this._displacementVector = BABYLON.Vector3.Zero();
  49807. this._radius = BABYLON.Vector3.One();
  49808. this._retry = 0;
  49809. this._basePointWorld = BABYLON.Vector3.Zero();
  49810. this._velocityWorld = BABYLON.Vector3.Zero();
  49811. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49812. this._collisionMask = -1;
  49813. }
  49814. Object.defineProperty(Collider.prototype, "collisionMask", {
  49815. get: function () {
  49816. return this._collisionMask;
  49817. },
  49818. set: function (mask) {
  49819. this._collisionMask = !isNaN(mask) ? mask : -1;
  49820. },
  49821. enumerable: true,
  49822. configurable: true
  49823. });
  49824. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49825. /**
  49826. * Gets the plane normal used to compute the sliding response (in local space)
  49827. */
  49828. get: function () {
  49829. return this._slidePlaneNormal;
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. // Methods
  49835. Collider.prototype._initialize = function (source, dir, e) {
  49836. this._velocity = dir;
  49837. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49838. this._basePoint = source;
  49839. source.multiplyToRef(this._radius, this._basePointWorld);
  49840. dir.multiplyToRef(this._radius, this._velocityWorld);
  49841. this._velocityWorldLength = this._velocityWorld.length();
  49842. this._epsilon = e;
  49843. this.collisionFound = false;
  49844. };
  49845. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49846. pa.subtractToRef(point, this._tempVector);
  49847. pb.subtractToRef(point, this._tempVector2);
  49848. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49849. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49850. if (d < 0)
  49851. return false;
  49852. pc.subtractToRef(point, this._tempVector3);
  49853. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49854. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49855. if (d < 0)
  49856. return false;
  49857. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49858. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49859. return d >= 0;
  49860. };
  49861. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49862. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49863. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49864. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49865. return false;
  49866. }
  49867. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49868. return false;
  49869. return true;
  49870. };
  49871. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49872. var t0;
  49873. var embeddedInPlane = false;
  49874. //defensive programming, actually not needed.
  49875. if (!trianglePlaneArray) {
  49876. trianglePlaneArray = [];
  49877. }
  49878. if (!trianglePlaneArray[faceIndex]) {
  49879. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49880. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49881. }
  49882. var trianglePlane = trianglePlaneArray[faceIndex];
  49883. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49884. return;
  49885. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49886. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49887. if (normalDotVelocity == 0) {
  49888. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49889. return;
  49890. embeddedInPlane = true;
  49891. t0 = 0;
  49892. }
  49893. else {
  49894. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49895. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49896. if (t0 > t1) {
  49897. var temp = t1;
  49898. t1 = t0;
  49899. t0 = temp;
  49900. }
  49901. if (t0 > 1.0 || t1 < 0.0)
  49902. return;
  49903. if (t0 < 0)
  49904. t0 = 0;
  49905. if (t0 > 1.0)
  49906. t0 = 1.0;
  49907. }
  49908. this._collisionPoint.copyFromFloats(0, 0, 0);
  49909. var found = false;
  49910. var t = 1.0;
  49911. if (!embeddedInPlane) {
  49912. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49913. this._velocity.scaleToRef(t0, this._tempVector);
  49914. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49915. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49916. found = true;
  49917. t = t0;
  49918. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49919. }
  49920. }
  49921. if (!found) {
  49922. var velocitySquaredLength = this._velocity.lengthSquared();
  49923. var a = velocitySquaredLength;
  49924. this._basePoint.subtractToRef(p1, this._tempVector);
  49925. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49926. var c = this._tempVector.lengthSquared() - 1.0;
  49927. var lowestRoot = getLowestRoot(a, b, c, t);
  49928. if (lowestRoot.found) {
  49929. t = lowestRoot.root;
  49930. found = true;
  49931. this._collisionPoint.copyFrom(p1);
  49932. }
  49933. this._basePoint.subtractToRef(p2, this._tempVector);
  49934. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49935. c = this._tempVector.lengthSquared() - 1.0;
  49936. lowestRoot = getLowestRoot(a, b, c, t);
  49937. if (lowestRoot.found) {
  49938. t = lowestRoot.root;
  49939. found = true;
  49940. this._collisionPoint.copyFrom(p2);
  49941. }
  49942. this._basePoint.subtractToRef(p3, this._tempVector);
  49943. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49944. c = this._tempVector.lengthSquared() - 1.0;
  49945. lowestRoot = getLowestRoot(a, b, c, t);
  49946. if (lowestRoot.found) {
  49947. t = lowestRoot.root;
  49948. found = true;
  49949. this._collisionPoint.copyFrom(p3);
  49950. }
  49951. p2.subtractToRef(p1, this._edge);
  49952. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49953. var edgeSquaredLength = this._edge.lengthSquared();
  49954. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49955. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49956. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49957. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49958. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49959. lowestRoot = getLowestRoot(a, b, c, t);
  49960. if (lowestRoot.found) {
  49961. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49962. if (f >= 0.0 && f <= 1.0) {
  49963. t = lowestRoot.root;
  49964. found = true;
  49965. this._edge.scaleInPlace(f);
  49966. p1.addToRef(this._edge, this._collisionPoint);
  49967. }
  49968. }
  49969. p3.subtractToRef(p2, this._edge);
  49970. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49971. edgeSquaredLength = this._edge.lengthSquared();
  49972. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49973. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49974. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49975. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49976. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49977. lowestRoot = getLowestRoot(a, b, c, t);
  49978. if (lowestRoot.found) {
  49979. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49980. if (f >= 0.0 && f <= 1.0) {
  49981. t = lowestRoot.root;
  49982. found = true;
  49983. this._edge.scaleInPlace(f);
  49984. p2.addToRef(this._edge, this._collisionPoint);
  49985. }
  49986. }
  49987. p1.subtractToRef(p3, this._edge);
  49988. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49989. edgeSquaredLength = this._edge.lengthSquared();
  49990. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49991. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49992. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49993. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49994. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49995. lowestRoot = getLowestRoot(a, b, c, t);
  49996. if (lowestRoot.found) {
  49997. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49998. if (f >= 0.0 && f <= 1.0) {
  49999. t = lowestRoot.root;
  50000. found = true;
  50001. this._edge.scaleInPlace(f);
  50002. p3.addToRef(this._edge, this._collisionPoint);
  50003. }
  50004. }
  50005. }
  50006. if (found) {
  50007. var distToCollision = t * this._velocity.length();
  50008. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50009. if (!this.intersectionPoint) {
  50010. this.intersectionPoint = this._collisionPoint.clone();
  50011. }
  50012. else {
  50013. this.intersectionPoint.copyFrom(this._collisionPoint);
  50014. }
  50015. this._nearestDistance = distToCollision;
  50016. this.collisionFound = true;
  50017. }
  50018. }
  50019. };
  50020. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50021. for (var i = indexStart; i < indexEnd; i += 3) {
  50022. var p1 = pts[indices[i] - decal];
  50023. var p2 = pts[indices[i + 1] - decal];
  50024. var p3 = pts[indices[i + 2] - decal];
  50025. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50026. }
  50027. };
  50028. Collider.prototype._getResponse = function (pos, vel) {
  50029. pos.addToRef(vel, this._destinationPoint);
  50030. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50031. this._basePoint.addToRef(vel, pos);
  50032. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50033. this._slidePlaneNormal.normalize();
  50034. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50035. pos.addInPlace(this._displacementVector);
  50036. this.intersectionPoint.addInPlace(this._displacementVector);
  50037. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50038. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50039. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50040. };
  50041. return Collider;
  50042. }());
  50043. BABYLON.Collider = Collider;
  50044. })(BABYLON || (BABYLON = {}));
  50045. //# sourceMappingURL=babylon.collider.js.map
  50046. var BABYLON;
  50047. (function (BABYLON) {
  50048. //WebWorker code will be inserted to this variable.
  50049. BABYLON.CollisionWorker = "";
  50050. var WorkerTaskType;
  50051. (function (WorkerTaskType) {
  50052. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50053. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50054. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50055. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50056. var WorkerReplyType;
  50057. (function (WorkerReplyType) {
  50058. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50059. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50060. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50061. var CollisionCoordinatorWorker = /** @class */ (function () {
  50062. function CollisionCoordinatorWorker() {
  50063. var _this = this;
  50064. this._scaledPosition = BABYLON.Vector3.Zero();
  50065. this._scaledVelocity = BABYLON.Vector3.Zero();
  50066. this.onMeshUpdated = function (transformNode) {
  50067. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50068. };
  50069. this.onGeometryUpdated = function (geometry) {
  50070. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50071. };
  50072. this._afterRender = function () {
  50073. if (!_this._init)
  50074. return;
  50075. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50076. return;
  50077. }
  50078. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50079. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50080. if (_this._runningUpdated > 4) {
  50081. return;
  50082. }
  50083. ++_this._runningUpdated;
  50084. var payload = {
  50085. updatedMeshes: _this._addUpdateMeshesList,
  50086. updatedGeometries: _this._addUpdateGeometriesList,
  50087. removedGeometries: _this._toRemoveGeometryArray,
  50088. removedMeshes: _this._toRemoveMeshesArray
  50089. };
  50090. var message = {
  50091. payload: payload,
  50092. taskType: WorkerTaskType.UPDATE
  50093. };
  50094. var serializable = [];
  50095. for (var id in payload.updatedGeometries) {
  50096. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50097. //prepare transferables
  50098. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50099. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50100. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50101. }
  50102. }
  50103. _this._worker.postMessage(message, serializable);
  50104. _this._addUpdateMeshesList = {};
  50105. _this._addUpdateGeometriesList = {};
  50106. _this._toRemoveGeometryArray = [];
  50107. _this._toRemoveMeshesArray = [];
  50108. };
  50109. this._onMessageFromWorker = function (e) {
  50110. var returnData = e.data;
  50111. if (returnData.error != WorkerReplyType.SUCCESS) {
  50112. //TODO what errors can be returned from the worker?
  50113. BABYLON.Tools.Warn("error returned from worker!");
  50114. return;
  50115. }
  50116. switch (returnData.taskType) {
  50117. case WorkerTaskType.INIT:
  50118. _this._init = true;
  50119. //Update the worked with ALL of the scene's current state
  50120. _this._scene.meshes.forEach(function (mesh) {
  50121. _this.onMeshAdded(mesh);
  50122. });
  50123. _this._scene.getGeometries().forEach(function (geometry) {
  50124. _this.onGeometryAdded(geometry);
  50125. });
  50126. break;
  50127. case WorkerTaskType.UPDATE:
  50128. _this._runningUpdated--;
  50129. break;
  50130. case WorkerTaskType.COLLIDE:
  50131. var returnPayload = returnData.payload;
  50132. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50133. return;
  50134. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50135. if (callback) {
  50136. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50137. if (mesh) {
  50138. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50139. }
  50140. }
  50141. //cleanup
  50142. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50143. break;
  50144. }
  50145. };
  50146. this._collisionsCallbackArray = [];
  50147. this._init = false;
  50148. this._runningUpdated = 0;
  50149. this._addUpdateMeshesList = {};
  50150. this._addUpdateGeometriesList = {};
  50151. this._toRemoveGeometryArray = [];
  50152. this._toRemoveMeshesArray = [];
  50153. }
  50154. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50155. if (!this._init)
  50156. return;
  50157. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50158. return;
  50159. position.divideToRef(collider._radius, this._scaledPosition);
  50160. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50161. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50162. var payload = {
  50163. collider: {
  50164. position: this._scaledPosition.asArray(),
  50165. velocity: this._scaledVelocity.asArray(),
  50166. radius: collider._radius.asArray()
  50167. },
  50168. collisionId: collisionIndex,
  50169. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50170. maximumRetry: maximumRetry
  50171. };
  50172. var message = {
  50173. payload: payload,
  50174. taskType: WorkerTaskType.COLLIDE
  50175. };
  50176. this._worker.postMessage(message);
  50177. };
  50178. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50179. this._scene = scene;
  50180. this._scene.registerAfterRender(this._afterRender);
  50181. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50182. this._worker = new Worker(workerUrl);
  50183. this._worker.onmessage = this._onMessageFromWorker;
  50184. var message = {
  50185. payload: {},
  50186. taskType: WorkerTaskType.INIT
  50187. };
  50188. this._worker.postMessage(message);
  50189. };
  50190. CollisionCoordinatorWorker.prototype.destroy = function () {
  50191. this._scene.unregisterAfterRender(this._afterRender);
  50192. this._worker.terminate();
  50193. };
  50194. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50195. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50196. this.onMeshUpdated(mesh);
  50197. };
  50198. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50199. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50200. };
  50201. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50202. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50203. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50204. this.onGeometryUpdated(geometry);
  50205. };
  50206. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50207. this._toRemoveGeometryArray.push(geometry.id);
  50208. };
  50209. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50210. var submeshes = [];
  50211. if (mesh.subMeshes) {
  50212. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50213. var boundingInfo = sm.getBoundingInfo();
  50214. return {
  50215. position: idx,
  50216. verticesStart: sm.verticesStart,
  50217. verticesCount: sm.verticesCount,
  50218. indexStart: sm.indexStart,
  50219. indexCount: sm.indexCount,
  50220. hasMaterial: !!sm.getMaterial(),
  50221. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50222. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50223. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50224. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50225. };
  50226. });
  50227. }
  50228. var geometryId = null;
  50229. if (mesh instanceof BABYLON.Mesh) {
  50230. var geometry = mesh.geometry;
  50231. geometryId = geometry ? geometry.id : null;
  50232. }
  50233. else if (mesh instanceof BABYLON.InstancedMesh) {
  50234. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50235. geometryId = geometry ? geometry.id : null;
  50236. }
  50237. var boundingInfo = mesh.getBoundingInfo();
  50238. return {
  50239. uniqueId: mesh.uniqueId,
  50240. id: mesh.id,
  50241. name: mesh.name,
  50242. geometryId: geometryId,
  50243. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50244. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50245. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50246. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50247. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50248. subMeshes: submeshes,
  50249. checkCollisions: mesh.checkCollisions
  50250. };
  50251. };
  50252. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50253. return {
  50254. id: geometry.id,
  50255. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50256. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50257. indices: new Uint32Array(geometry.getIndices() || []),
  50258. };
  50259. };
  50260. return CollisionCoordinatorWorker;
  50261. }());
  50262. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50263. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50264. function CollisionCoordinatorLegacy() {
  50265. this._scaledPosition = BABYLON.Vector3.Zero();
  50266. this._scaledVelocity = BABYLON.Vector3.Zero();
  50267. this._finalPosition = BABYLON.Vector3.Zero();
  50268. }
  50269. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50270. position.divideToRef(collider._radius, this._scaledPosition);
  50271. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50272. collider.collidedMesh = null;
  50273. collider._retry = 0;
  50274. collider._initialVelocity = this._scaledVelocity;
  50275. collider._initialPosition = this._scaledPosition;
  50276. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50277. this._finalPosition.multiplyInPlace(collider._radius);
  50278. //run the callback
  50279. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50280. };
  50281. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50282. this._scene = scene;
  50283. };
  50284. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50285. //Legacy need no destruction method.
  50286. };
  50287. //No update in legacy mode
  50288. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50289. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50290. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50291. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50292. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50293. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50294. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50295. if (excludedMesh === void 0) { excludedMesh = null; }
  50296. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50297. if (collider._retry >= maximumRetry) {
  50298. finalPosition.copyFrom(position);
  50299. return;
  50300. }
  50301. // Check if this is a mesh else camera or -1
  50302. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50303. collider._initialize(position, velocity, closeDistance);
  50304. // Check all meshes
  50305. for (var index = 0; index < this._scene.meshes.length; index++) {
  50306. var mesh = this._scene.meshes[index];
  50307. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50308. mesh._checkCollision(collider);
  50309. }
  50310. }
  50311. if (!collider.collisionFound) {
  50312. position.addToRef(velocity, finalPosition);
  50313. return;
  50314. }
  50315. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50316. collider._getResponse(position, velocity);
  50317. }
  50318. if (velocity.length() <= closeDistance) {
  50319. finalPosition.copyFrom(position);
  50320. return;
  50321. }
  50322. collider._retry++;
  50323. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50324. };
  50325. return CollisionCoordinatorLegacy;
  50326. }());
  50327. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50328. })(BABYLON || (BABYLON = {}));
  50329. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50330. var BABYLON;
  50331. (function (BABYLON) {
  50332. /**
  50333. * A particle represents one of the element emitted by a particle system.
  50334. * This is mainly define by its coordinates, direction, velocity and age.
  50335. */
  50336. var Particle = /** @class */ (function () {
  50337. /**
  50338. * Creates a new instance of @see Particle
  50339. * @param particleSystem the particle system the particle belongs to
  50340. */
  50341. function Particle(particleSystem) {
  50342. this.particleSystem = particleSystem;
  50343. /**
  50344. * The world position of the particle in the scene.
  50345. */
  50346. this.position = BABYLON.Vector3.Zero();
  50347. /**
  50348. * The world direction of the particle in the scene.
  50349. */
  50350. this.direction = BABYLON.Vector3.Zero();
  50351. /**
  50352. * The color of the particle.
  50353. */
  50354. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50355. /**
  50356. * The color change of the particle per step.
  50357. */
  50358. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50359. /**
  50360. * Defines how long will the life of the particle be.
  50361. */
  50362. this.lifeTime = 1.0;
  50363. /**
  50364. * The current age of the particle.
  50365. */
  50366. this.age = 0;
  50367. /**
  50368. * The current size of the particle.
  50369. */
  50370. this.size = 0;
  50371. /**
  50372. * The current angle of the particle.
  50373. */
  50374. this.angle = 0;
  50375. /**
  50376. * Defines how fast is the angle changing.
  50377. */
  50378. this.angularSpeed = 0;
  50379. /**
  50380. * Defines the cell index used by the particle to be rendered from a sprite.
  50381. */
  50382. this.cellIndex = 0;
  50383. this._currentFrameCounter = 0;
  50384. if (!this.particleSystem.isAnimationSheetEnabled) {
  50385. return;
  50386. }
  50387. this.cellIndex = this.particleSystem.startSpriteCellID;
  50388. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50389. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50390. }
  50391. else {
  50392. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50393. }
  50394. }
  50395. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50396. // (ageOffset / scaledUpdateSpeed) / available cells
  50397. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50398. this._currentFrameCounter += scaledUpdateSpeed;
  50399. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50400. this._currentFrameCounter = 0;
  50401. this.cellIndex++;
  50402. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50403. this.cellIndex = this.particleSystem.endSpriteCellID;
  50404. }
  50405. }
  50406. };
  50407. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50408. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50409. this.cellIndex++;
  50410. this._currentFrameCounter = 0;
  50411. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50412. if (this.particleSystem.spriteCellLoop) {
  50413. this.cellIndex = this.particleSystem.startSpriteCellID;
  50414. }
  50415. else {
  50416. this.cellIndex = this.particleSystem.endSpriteCellID;
  50417. }
  50418. }
  50419. }
  50420. else {
  50421. this._currentFrameCounter++;
  50422. }
  50423. };
  50424. /**
  50425. * Copy the properties of particle to another one.
  50426. * @param other the particle to copy the information to.
  50427. */
  50428. Particle.prototype.copyTo = function (other) {
  50429. other.position.copyFrom(this.position);
  50430. other.direction.copyFrom(this.direction);
  50431. other.color.copyFrom(this.color);
  50432. other.colorStep.copyFrom(this.colorStep);
  50433. other.lifeTime = this.lifeTime;
  50434. other.age = this.age;
  50435. other.size = this.size;
  50436. other.angle = this.angle;
  50437. other.angularSpeed = this.angularSpeed;
  50438. other.particleSystem = this.particleSystem;
  50439. other.cellIndex = this.cellIndex;
  50440. };
  50441. return Particle;
  50442. }());
  50443. BABYLON.Particle = Particle;
  50444. })(BABYLON || (BABYLON = {}));
  50445. //# sourceMappingURL=babylon.particle.js.map
  50446. var BABYLON;
  50447. (function (BABYLON) {
  50448. /**
  50449. * This represents a particle system in Babylon.
  50450. * 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.
  50451. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50452. * @example https://doc.babylonjs.com/babylon101/particles
  50453. */
  50454. var ParticleSystem = /** @class */ (function () {
  50455. /**
  50456. * Instantiates a particle system.
  50457. * 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.
  50458. * @param name The name of the particle system
  50459. * @param capacity The max number of particles alive at the same time
  50460. * @param scene The scene the particle system belongs to
  50461. * @param customEffect a custom effect used to change the way particles are rendered by default
  50462. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50463. * @param epsilon Offset used to render the particles
  50464. */
  50465. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50466. if (customEffect === void 0) { customEffect = null; }
  50467. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50468. if (epsilon === void 0) { epsilon = 0.01; }
  50469. var _this = this;
  50470. /**
  50471. * List of animations used by the particle system.
  50472. */
  50473. this.animations = [];
  50474. /**
  50475. * The rendering group used by the Particle system to chose when to render.
  50476. */
  50477. this.renderingGroupId = 0;
  50478. /**
  50479. * The emitter represents the Mesh or position we are attaching the particle system to.
  50480. */
  50481. this.emitter = null;
  50482. /**
  50483. * The maximum number of particles to emit per frame
  50484. */
  50485. this.emitRate = 10;
  50486. /**
  50487. * If you want to launch only a few particles at once, that can be done, as well.
  50488. */
  50489. this.manualEmitCount = -1;
  50490. /**
  50491. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50492. */
  50493. this.updateSpeed = 0.01;
  50494. /**
  50495. * The amount of time the particle system is running (depends of the overall update speed).
  50496. */
  50497. this.targetStopDuration = 0;
  50498. /**
  50499. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50500. */
  50501. this.disposeOnStop = false;
  50502. /**
  50503. * Minimum power of emitting particles.
  50504. */
  50505. this.minEmitPower = 1;
  50506. /**
  50507. * Maximum power of emitting particles.
  50508. */
  50509. this.maxEmitPower = 1;
  50510. /**
  50511. * Minimum life time of emitting particles.
  50512. */
  50513. this.minLifeTime = 1;
  50514. /**
  50515. * Maximum life time of emitting particles.
  50516. */
  50517. this.maxLifeTime = 1;
  50518. /**
  50519. * Minimum Size of emitting particles.
  50520. */
  50521. this.minSize = 1;
  50522. /**
  50523. * Maximum Size of emitting particles.
  50524. */
  50525. this.maxSize = 1;
  50526. /**
  50527. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50528. */
  50529. this.minAngularSpeed = 0;
  50530. /**
  50531. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50532. */
  50533. this.maxAngularSpeed = 0;
  50534. /**
  50535. * The layer mask we are rendering the particles through.
  50536. */
  50537. this.layerMask = 0x0FFFFFFF;
  50538. /**
  50539. * This can help using your own shader to render the particle system.
  50540. * The according effect will be created
  50541. */
  50542. this.customShader = null;
  50543. /**
  50544. * By default particle system starts as soon as they are created. This prevents the
  50545. * automatic start to happen and let you decide when to start emitting particles.
  50546. */
  50547. this.preventAutoStart = false;
  50548. /**
  50549. * Callback triggered when the particle animation is ending.
  50550. */
  50551. this.onAnimationEnd = null;
  50552. /**
  50553. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50554. */
  50555. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50556. /**
  50557. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50558. * to override the particles.
  50559. */
  50560. this.forceDepthWrite = false;
  50561. /**
  50562. * You can use gravity if you want to give an orientation to your particles.
  50563. */
  50564. this.gravity = BABYLON.Vector3.Zero();
  50565. /**
  50566. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50567. */
  50568. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50569. /**
  50570. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50571. */
  50572. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50573. /**
  50574. * Color the particle will have at the end of its lifetime.
  50575. */
  50576. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50577. /**
  50578. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50579. */
  50580. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50581. /**
  50582. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50583. */
  50584. this.spriteCellLoop = true;
  50585. /**
  50586. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50587. */
  50588. this.spriteCellChangeSpeed = 0;
  50589. /**
  50590. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50591. */
  50592. this.startSpriteCellID = 0;
  50593. /**
  50594. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50595. */
  50596. this.endSpriteCellID = 0;
  50597. /**
  50598. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50599. */
  50600. this.spriteCellWidth = 0;
  50601. /**
  50602. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50603. */
  50604. this.spriteCellHeight = 0;
  50605. /**
  50606. * An event triggered when the system is disposed.
  50607. */
  50608. this.onDisposeObservable = new BABYLON.Observable();
  50609. this._particles = new Array();
  50610. this._stockParticles = new Array();
  50611. this._newPartsExcess = 0;
  50612. this._vertexBuffers = {};
  50613. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50614. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50615. this._scaledDirection = BABYLON.Vector3.Zero();
  50616. this._scaledGravity = BABYLON.Vector3.Zero();
  50617. this._currentRenderId = -1;
  50618. this._started = false;
  50619. this._stopped = false;
  50620. this._actualFrame = 0;
  50621. this._vertexBufferSize = 11;
  50622. this._appendParticleVertexes = null;
  50623. this.id = name;
  50624. this.name = name;
  50625. this._capacity = capacity;
  50626. this._epsilon = epsilon;
  50627. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50628. if (isAnimationSheetEnabled) {
  50629. this._vertexBufferSize = 12;
  50630. }
  50631. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50632. this._customEffect = customEffect;
  50633. scene.particleSystems.push(this);
  50634. this._createIndexBuffer();
  50635. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50636. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50637. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50638. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50639. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50640. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50641. if (this._isAnimationSheetEnabled) {
  50642. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50643. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50644. }
  50645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50646. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50647. this._vertexBuffers["options"] = options;
  50648. // Default emitter type
  50649. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50650. this.updateFunction = function (particles) {
  50651. for (var index = 0; index < particles.length; index++) {
  50652. var particle = particles[index];
  50653. particle.age += _this._scaledUpdateSpeed;
  50654. if (particle.age >= particle.lifeTime) {
  50655. _this.recycleParticle(particle);
  50656. index--;
  50657. continue;
  50658. }
  50659. else {
  50660. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50661. particle.color.addInPlace(_this._scaledColorStep);
  50662. if (particle.color.a < 0)
  50663. particle.color.a = 0;
  50664. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50665. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50666. particle.position.addInPlace(_this._scaledDirection);
  50667. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50668. particle.direction.addInPlace(_this._scaledGravity);
  50669. if (_this._isAnimationSheetEnabled) {
  50670. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50671. }
  50672. }
  50673. }
  50674. };
  50675. }
  50676. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50677. /**
  50678. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50679. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50680. */
  50681. get: function () {
  50682. if (this.particleEmitterType.direction1) {
  50683. return this.particleEmitterType.direction1;
  50684. }
  50685. return BABYLON.Vector3.Zero();
  50686. },
  50687. set: function (value) {
  50688. if (this.particleEmitterType.direction1) {
  50689. this.particleEmitterType.direction1 = value;
  50690. }
  50691. },
  50692. enumerable: true,
  50693. configurable: true
  50694. });
  50695. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50696. /**
  50697. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50698. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50699. */
  50700. get: function () {
  50701. if (this.particleEmitterType.direction2) {
  50702. return this.particleEmitterType.direction2;
  50703. }
  50704. return BABYLON.Vector3.Zero();
  50705. },
  50706. set: function (value) {
  50707. if (this.particleEmitterType.direction2) {
  50708. this.particleEmitterType.direction2 = value;
  50709. }
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50715. /**
  50716. * 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.
  50717. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50718. */
  50719. get: function () {
  50720. if (this.particleEmitterType.minEmitBox) {
  50721. return this.particleEmitterType.minEmitBox;
  50722. }
  50723. return BABYLON.Vector3.Zero();
  50724. },
  50725. set: function (value) {
  50726. if (this.particleEmitterType.minEmitBox) {
  50727. this.particleEmitterType.minEmitBox = value;
  50728. }
  50729. },
  50730. enumerable: true,
  50731. configurable: true
  50732. });
  50733. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50734. /**
  50735. * 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.
  50736. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50737. */
  50738. get: function () {
  50739. if (this.particleEmitterType.maxEmitBox) {
  50740. return this.particleEmitterType.maxEmitBox;
  50741. }
  50742. return BABYLON.Vector3.Zero();
  50743. },
  50744. set: function (value) {
  50745. if (this.particleEmitterType.maxEmitBox) {
  50746. this.particleEmitterType.maxEmitBox = value;
  50747. }
  50748. },
  50749. enumerable: true,
  50750. configurable: true
  50751. });
  50752. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50753. /**
  50754. * Sets a callback that will be triggered when the system is disposed.
  50755. */
  50756. set: function (callback) {
  50757. if (this._onDisposeObserver) {
  50758. this.onDisposeObservable.remove(this._onDisposeObserver);
  50759. }
  50760. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50761. },
  50762. enumerable: true,
  50763. configurable: true
  50764. });
  50765. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50766. /**
  50767. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50768. */
  50769. get: function () {
  50770. return this._isAnimationSheetEnabled;
  50771. },
  50772. enumerable: true,
  50773. configurable: true
  50774. });
  50775. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50776. /**
  50777. * Gets the current list of active particles
  50778. */
  50779. get: function () {
  50780. return this._particles;
  50781. },
  50782. enumerable: true,
  50783. configurable: true
  50784. });
  50785. /**
  50786. * Returns the string "ParticleSystem"
  50787. * @returns a string containing the class name
  50788. */
  50789. ParticleSystem.prototype.getClassName = function () {
  50790. return "ParticleSystem";
  50791. };
  50792. ParticleSystem.prototype._createIndexBuffer = function () {
  50793. var indices = [];
  50794. var index = 0;
  50795. for (var count = 0; count < this._capacity; count++) {
  50796. indices.push(index);
  50797. indices.push(index + 1);
  50798. indices.push(index + 2);
  50799. indices.push(index);
  50800. indices.push(index + 2);
  50801. indices.push(index + 3);
  50802. index += 4;
  50803. }
  50804. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50805. };
  50806. /**
  50807. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50808. * Its lifetime will start back at 0.
  50809. * @param particle The particle to recycle
  50810. */
  50811. ParticleSystem.prototype.recycleParticle = function (particle) {
  50812. var lastParticle = this._particles.pop();
  50813. if (lastParticle !== particle) {
  50814. lastParticle.copyTo(particle);
  50815. this._stockParticles.push(lastParticle);
  50816. }
  50817. };
  50818. /**
  50819. * Gets the maximum number of particles active at the same time.
  50820. * @returns The max number of active particles.
  50821. */
  50822. ParticleSystem.prototype.getCapacity = function () {
  50823. return this._capacity;
  50824. };
  50825. /**
  50826. * Gets Wether there are still active particles in the system.
  50827. * @returns True if it is alive, otherwise false.
  50828. */
  50829. ParticleSystem.prototype.isAlive = function () {
  50830. return this._alive;
  50831. };
  50832. /**
  50833. * Gets Wether the system has been started.
  50834. * @returns True if it has been started, otherwise false.
  50835. */
  50836. ParticleSystem.prototype.isStarted = function () {
  50837. return this._started;
  50838. };
  50839. /**
  50840. * Starts the particle system and begins to emit.
  50841. */
  50842. ParticleSystem.prototype.start = function () {
  50843. this._started = true;
  50844. this._stopped = false;
  50845. this._actualFrame = 0;
  50846. };
  50847. /**
  50848. * Stops the particle system.
  50849. */
  50850. ParticleSystem.prototype.stop = function () {
  50851. this._stopped = true;
  50852. };
  50853. /**
  50854. * Remove all active particles
  50855. */
  50856. ParticleSystem.prototype.reset = function () {
  50857. this._stockParticles = [];
  50858. this._particles = [];
  50859. };
  50860. /**
  50861. * @ignore (for internal use only)
  50862. */
  50863. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50864. var offset = index * this._vertexBufferSize;
  50865. this._vertexData[offset] = particle.position.x;
  50866. this._vertexData[offset + 1] = particle.position.y;
  50867. this._vertexData[offset + 2] = particle.position.z;
  50868. this._vertexData[offset + 3] = particle.color.r;
  50869. this._vertexData[offset + 4] = particle.color.g;
  50870. this._vertexData[offset + 5] = particle.color.b;
  50871. this._vertexData[offset + 6] = particle.color.a;
  50872. this._vertexData[offset + 7] = particle.angle;
  50873. this._vertexData[offset + 8] = particle.size;
  50874. this._vertexData[offset + 9] = offsetX;
  50875. this._vertexData[offset + 10] = offsetY;
  50876. };
  50877. /**
  50878. * @ignore (for internal use only)
  50879. */
  50880. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50881. if (offsetX === 0)
  50882. offsetX = this._epsilon;
  50883. else if (offsetX === 1)
  50884. offsetX = 1 - this._epsilon;
  50885. if (offsetY === 0)
  50886. offsetY = this._epsilon;
  50887. else if (offsetY === 1)
  50888. offsetY = 1 - this._epsilon;
  50889. var offset = index * this._vertexBufferSize;
  50890. this._vertexData[offset] = particle.position.x;
  50891. this._vertexData[offset + 1] = particle.position.y;
  50892. this._vertexData[offset + 2] = particle.position.z;
  50893. this._vertexData[offset + 3] = particle.color.r;
  50894. this._vertexData[offset + 4] = particle.color.g;
  50895. this._vertexData[offset + 5] = particle.color.b;
  50896. this._vertexData[offset + 6] = particle.color.a;
  50897. this._vertexData[offset + 7] = particle.angle;
  50898. this._vertexData[offset + 8] = particle.size;
  50899. this._vertexData[offset + 9] = offsetX;
  50900. this._vertexData[offset + 10] = offsetY;
  50901. this._vertexData[offset + 11] = particle.cellIndex;
  50902. };
  50903. ParticleSystem.prototype._update = function (newParticles) {
  50904. // Update current
  50905. this._alive = this._particles.length > 0;
  50906. this.updateFunction(this._particles);
  50907. // Add new ones
  50908. var worldMatrix;
  50909. if (this.emitter.position) {
  50910. var emitterMesh = this.emitter;
  50911. worldMatrix = emitterMesh.getWorldMatrix();
  50912. }
  50913. else {
  50914. var emitterPosition = this.emitter;
  50915. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50916. }
  50917. var particle;
  50918. for (var index = 0; index < newParticles; index++) {
  50919. if (this._particles.length === this._capacity) {
  50920. break;
  50921. }
  50922. if (this._stockParticles.length !== 0) {
  50923. particle = this._stockParticles.pop();
  50924. particle.age = 0;
  50925. particle.cellIndex = this.startSpriteCellID;
  50926. }
  50927. else {
  50928. particle = new BABYLON.Particle(this);
  50929. }
  50930. this._particles.push(particle);
  50931. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50932. if (this.startPositionFunction) {
  50933. this.startPositionFunction(worldMatrix, particle.position, particle);
  50934. }
  50935. else {
  50936. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50937. }
  50938. if (this.startDirectionFunction) {
  50939. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50940. }
  50941. else {
  50942. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50943. }
  50944. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50945. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50946. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50947. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50948. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50949. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50950. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50951. }
  50952. };
  50953. ParticleSystem.prototype._getEffect = function () {
  50954. if (this._customEffect) {
  50955. return this._customEffect;
  50956. }
  50957. ;
  50958. var defines = [];
  50959. if (this._scene.clipPlane) {
  50960. defines.push("#define CLIPPLANE");
  50961. }
  50962. if (this._isAnimationSheetEnabled) {
  50963. defines.push("#define ANIMATESHEET");
  50964. }
  50965. // Effect
  50966. var join = defines.join("\n");
  50967. if (this._cachedDefines !== join) {
  50968. this._cachedDefines = join;
  50969. var attributesNamesOrOptions;
  50970. var effectCreationOption;
  50971. if (this._isAnimationSheetEnabled) {
  50972. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50973. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50974. }
  50975. else {
  50976. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50977. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50978. }
  50979. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50980. }
  50981. return this._effect;
  50982. };
  50983. /**
  50984. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50985. */
  50986. ParticleSystem.prototype.animate = function () {
  50987. if (!this._started)
  50988. return;
  50989. var effect = this._getEffect();
  50990. // Check
  50991. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50992. return;
  50993. if (this._currentRenderId === this._scene.getRenderId()) {
  50994. return;
  50995. }
  50996. this._currentRenderId = this._scene.getRenderId();
  50997. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50998. // determine the number of particles we need to create
  50999. var newParticles;
  51000. if (this.manualEmitCount > -1) {
  51001. newParticles = this.manualEmitCount;
  51002. this._newPartsExcess = 0;
  51003. this.manualEmitCount = 0;
  51004. }
  51005. else {
  51006. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51007. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51008. }
  51009. if (this._newPartsExcess > 1.0) {
  51010. newParticles += this._newPartsExcess >> 0;
  51011. this._newPartsExcess -= this._newPartsExcess >> 0;
  51012. }
  51013. this._alive = false;
  51014. if (!this._stopped) {
  51015. this._actualFrame += this._scaledUpdateSpeed;
  51016. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51017. this.stop();
  51018. }
  51019. else {
  51020. newParticles = 0;
  51021. }
  51022. this._update(newParticles);
  51023. // Stopped?
  51024. if (this._stopped) {
  51025. if (!this._alive) {
  51026. this._started = false;
  51027. if (this.onAnimationEnd) {
  51028. this.onAnimationEnd();
  51029. }
  51030. if (this.disposeOnStop) {
  51031. this._scene._toBeDisposed.push(this);
  51032. }
  51033. }
  51034. }
  51035. // Animation sheet
  51036. if (this._isAnimationSheetEnabled) {
  51037. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51038. }
  51039. else {
  51040. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51041. }
  51042. // Update VBO
  51043. var offset = 0;
  51044. for (var index = 0; index < this._particles.length; index++) {
  51045. var particle = this._particles[index];
  51046. this._appendParticleVertexes(offset, particle);
  51047. offset += 4;
  51048. }
  51049. if (this._vertexBuffer) {
  51050. this._vertexBuffer.update(this._vertexData);
  51051. }
  51052. };
  51053. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51054. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51055. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51056. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51057. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51058. };
  51059. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51060. this._appendParticleVertex(offset++, particle, 0, 0);
  51061. this._appendParticleVertex(offset++, particle, 1, 0);
  51062. this._appendParticleVertex(offset++, particle, 1, 1);
  51063. this._appendParticleVertex(offset++, particle, 0, 1);
  51064. };
  51065. /**
  51066. * Rebuilds the particle system.
  51067. */
  51068. ParticleSystem.prototype.rebuild = function () {
  51069. this._createIndexBuffer();
  51070. if (this._vertexBuffer) {
  51071. this._vertexBuffer._rebuild();
  51072. }
  51073. };
  51074. /**
  51075. * Renders the particle system in its current state.
  51076. * @returns the current number of particles
  51077. */
  51078. ParticleSystem.prototype.render = function () {
  51079. var effect = this._getEffect();
  51080. // Check
  51081. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51082. return 0;
  51083. }
  51084. var engine = this._scene.getEngine();
  51085. // Render
  51086. engine.enableEffect(effect);
  51087. engine.setState(false);
  51088. var viewMatrix = this._scene.getViewMatrix();
  51089. effect.setTexture("diffuseSampler", this.particleTexture);
  51090. effect.setMatrix("view", viewMatrix);
  51091. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51092. if (this._isAnimationSheetEnabled) {
  51093. var baseSize = this.particleTexture.getBaseSize();
  51094. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51095. }
  51096. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51097. if (this._scene.clipPlane) {
  51098. var clipPlane = this._scene.clipPlane;
  51099. var invView = viewMatrix.clone();
  51100. invView.invert();
  51101. effect.setMatrix("invView", invView);
  51102. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51103. }
  51104. // VBOs
  51105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51106. // Draw order
  51107. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51108. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51109. }
  51110. else {
  51111. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51112. }
  51113. if (this.forceDepthWrite) {
  51114. engine.setDepthWrite(true);
  51115. }
  51116. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51117. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51118. return this._particles.length;
  51119. };
  51120. /**
  51121. * Disposes the particle system and free the associated resources
  51122. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51123. */
  51124. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51125. if (disposeTexture === void 0) { disposeTexture = true; }
  51126. if (this._vertexBuffer) {
  51127. this._vertexBuffer.dispose();
  51128. this._vertexBuffer = null;
  51129. }
  51130. if (this._indexBuffer) {
  51131. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51132. this._indexBuffer = null;
  51133. }
  51134. if (disposeTexture && this.particleTexture) {
  51135. this.particleTexture.dispose();
  51136. this.particleTexture = null;
  51137. }
  51138. // Remove from scene
  51139. var index = this._scene.particleSystems.indexOf(this);
  51140. if (index > -1) {
  51141. this._scene.particleSystems.splice(index, 1);
  51142. }
  51143. // Callback
  51144. this.onDisposeObservable.notifyObservers(this);
  51145. this.onDisposeObservable.clear();
  51146. };
  51147. /**
  51148. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51149. * @param radius The radius of the sphere to emit from
  51150. * @returns the emitter
  51151. */
  51152. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51153. if (radius === void 0) { radius = 1; }
  51154. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51155. this.particleEmitterType = particleEmitter;
  51156. return particleEmitter;
  51157. };
  51158. /**
  51159. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51160. * @param radius The radius of the sphere to emit from
  51161. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51162. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51163. * @returns the emitter
  51164. */
  51165. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51166. if (radius === void 0) { radius = 1; }
  51167. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51168. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51169. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51170. this.particleEmitterType = particleEmitter;
  51171. return particleEmitter;
  51172. };
  51173. /**
  51174. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51175. * @param radius The radius of the cone to emit from
  51176. * @param angle The base angle of the cone
  51177. * @returns the emitter
  51178. */
  51179. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51180. if (radius === void 0) { radius = 1; }
  51181. if (angle === void 0) { angle = Math.PI / 4; }
  51182. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51183. this.particleEmitterType = particleEmitter;
  51184. return particleEmitter;
  51185. };
  51186. // 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.
  51187. /**
  51188. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51189. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51190. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51191. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51192. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51193. * @returns the emitter
  51194. */
  51195. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51196. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51197. this.direction1 = direction1;
  51198. this.direction2 = direction2;
  51199. this.minEmitBox = minEmitBox;
  51200. this.maxEmitBox = maxEmitBox;
  51201. this.particleEmitterType = particleEmitter;
  51202. return particleEmitter;
  51203. };
  51204. /**
  51205. * Clones the particle system.
  51206. * @param name The name of the cloned object
  51207. * @param newEmitter The new emitter to use
  51208. * @returns the cloned particle system
  51209. */
  51210. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51211. var custom = null;
  51212. var program = null;
  51213. if (this.customShader != null) {
  51214. program = this.customShader;
  51215. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51216. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51217. }
  51218. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51219. result.customShader = program;
  51220. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51221. if (newEmitter === undefined) {
  51222. newEmitter = this.emitter;
  51223. }
  51224. result.emitter = newEmitter;
  51225. if (this.particleTexture) {
  51226. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51227. }
  51228. if (!this.preventAutoStart) {
  51229. result.start();
  51230. }
  51231. return result;
  51232. };
  51233. /**
  51234. * Serializes the particle system to a JSON object.
  51235. * @returns the JSON object
  51236. */
  51237. ParticleSystem.prototype.serialize = function () {
  51238. var serializationObject = {};
  51239. serializationObject.name = this.name;
  51240. serializationObject.id = this.id;
  51241. // Emitter
  51242. if (this.emitter.position) {
  51243. var emitterMesh = this.emitter;
  51244. serializationObject.emitterId = emitterMesh.id;
  51245. }
  51246. else {
  51247. var emitterPosition = this.emitter;
  51248. serializationObject.emitter = emitterPosition.asArray();
  51249. }
  51250. serializationObject.capacity = this.getCapacity();
  51251. if (this.particleTexture) {
  51252. serializationObject.textureName = this.particleTexture.name;
  51253. }
  51254. // Animations
  51255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51256. // Particle system
  51257. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51258. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51259. serializationObject.minSize = this.minSize;
  51260. serializationObject.maxSize = this.maxSize;
  51261. serializationObject.minEmitPower = this.minEmitPower;
  51262. serializationObject.maxEmitPower = this.maxEmitPower;
  51263. serializationObject.minLifeTime = this.minLifeTime;
  51264. serializationObject.maxLifeTime = this.maxLifeTime;
  51265. serializationObject.emitRate = this.emitRate;
  51266. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51267. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51268. serializationObject.gravity = this.gravity.asArray();
  51269. serializationObject.direction1 = this.direction1.asArray();
  51270. serializationObject.direction2 = this.direction2.asArray();
  51271. serializationObject.color1 = this.color1.asArray();
  51272. serializationObject.color2 = this.color2.asArray();
  51273. serializationObject.colorDead = this.colorDead.asArray();
  51274. serializationObject.updateSpeed = this.updateSpeed;
  51275. serializationObject.targetStopDuration = this.targetStopDuration;
  51276. serializationObject.textureMask = this.textureMask.asArray();
  51277. serializationObject.blendMode = this.blendMode;
  51278. serializationObject.customShader = this.customShader;
  51279. serializationObject.preventAutoStart = this.preventAutoStart;
  51280. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51281. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51282. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51283. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51284. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51285. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51286. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51287. // Emitter
  51288. if (this.particleEmitterType) {
  51289. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51290. }
  51291. return serializationObject;
  51292. };
  51293. /**
  51294. * Parses a JSON object to create a particle system.
  51295. * @param parsedParticleSystem The JSON object to parse
  51296. * @param scene The scene to create the particle system in
  51297. * @param rootUrl The root url to use to load external dependencies like texture
  51298. * @returns the Parsed particle system
  51299. */
  51300. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51301. var name = parsedParticleSystem.name;
  51302. var custom = null;
  51303. var program = null;
  51304. if (parsedParticleSystem.customShader) {
  51305. program = parsedParticleSystem.customShader;
  51306. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51307. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51308. }
  51309. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51310. particleSystem.customShader = program;
  51311. if (parsedParticleSystem.id) {
  51312. particleSystem.id = parsedParticleSystem.id;
  51313. }
  51314. // Auto start
  51315. if (parsedParticleSystem.preventAutoStart) {
  51316. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51317. }
  51318. // Texture
  51319. if (parsedParticleSystem.textureName) {
  51320. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51321. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51322. }
  51323. // Emitter
  51324. if (parsedParticleSystem.emitterId) {
  51325. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51326. }
  51327. else {
  51328. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51329. }
  51330. // Animations
  51331. if (parsedParticleSystem.animations) {
  51332. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51333. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51334. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51335. }
  51336. }
  51337. if (parsedParticleSystem.autoAnimate) {
  51338. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51339. }
  51340. // Particle system
  51341. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51342. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51343. particleSystem.minSize = parsedParticleSystem.minSize;
  51344. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51345. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51346. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51347. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51348. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51349. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51350. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51351. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51352. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51353. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51354. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51355. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51356. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51357. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51358. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51359. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51360. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51361. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51362. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51363. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51364. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51365. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51366. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51367. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51368. if (!particleSystem.preventAutoStart) {
  51369. particleSystem.start();
  51370. }
  51371. return particleSystem;
  51372. };
  51373. /**
  51374. * Source color is added to the destination color without alpha affecting the result.
  51375. */
  51376. ParticleSystem.BLENDMODE_ONEONE = 0;
  51377. /**
  51378. * Blend current color and particle color using particle’s alpha.
  51379. */
  51380. ParticleSystem.BLENDMODE_STANDARD = 1;
  51381. return ParticleSystem;
  51382. }());
  51383. BABYLON.ParticleSystem = ParticleSystem;
  51384. })(BABYLON || (BABYLON = {}));
  51385. //# sourceMappingURL=babylon.particleSystem.js.map
  51386. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51387. var BABYLON;
  51388. (function (BABYLON) {
  51389. /**
  51390. * Particle emitter emitting particles from the inside of a box.
  51391. * It emits the particles randomly between 2 given directions.
  51392. */
  51393. var BoxParticleEmitter = /** @class */ (function () {
  51394. /**
  51395. * Creates a new instance of @see BoxParticleEmitter
  51396. */
  51397. function BoxParticleEmitter() {
  51398. /**
  51399. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51400. */
  51401. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51402. /**
  51403. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51404. */
  51405. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51406. /**
  51407. * 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.
  51408. */
  51409. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51410. /**
  51411. * 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.
  51412. */
  51413. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51414. }
  51415. /**
  51416. * Called by the particle System when the direction is computed for the created particle.
  51417. * @param emitPower is the power of the particle (speed)
  51418. * @param worldMatrix is the world matrix of the particle system
  51419. * @param directionToUpdate is the direction vector to update with the result
  51420. * @param particle is the particle we are computed the direction for
  51421. */
  51422. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51423. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51424. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51425. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51426. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51427. };
  51428. /**
  51429. * Called by the particle System when the position is computed for the created particle.
  51430. * @param worldMatrix is the world matrix of the particle system
  51431. * @param positionToUpdate is the position vector to update with the result
  51432. * @param particle is the particle we are computed the position for
  51433. */
  51434. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51435. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51436. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51437. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51439. };
  51440. /**
  51441. * Clones the current emitter and returns a copy of it
  51442. * @returns the new emitter
  51443. */
  51444. BoxParticleEmitter.prototype.clone = function () {
  51445. var newOne = new BoxParticleEmitter();
  51446. BABYLON.Tools.DeepCopy(this, newOne);
  51447. return newOne;
  51448. };
  51449. /**
  51450. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51451. * @param effect defines the update shader
  51452. */
  51453. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51454. effect.setVector3("direction1", this.direction1);
  51455. effect.setVector3("direction2", this.direction2);
  51456. effect.setVector3("minEmitBox", this.minEmitBox);
  51457. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51458. };
  51459. /**
  51460. * Returns a string to use to update the GPU particles update shader
  51461. * @returns a string containng the defines string
  51462. */
  51463. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51464. return "#define BOXEMITTER";
  51465. };
  51466. /**
  51467. * Returns the string "BoxEmitter"
  51468. * @returns a string containing the class name
  51469. */
  51470. BoxParticleEmitter.prototype.getClassName = function () {
  51471. return "BoxEmitter";
  51472. };
  51473. /**
  51474. * Serializes the particle system to a JSON object.
  51475. * @returns the JSON object
  51476. */
  51477. BoxParticleEmitter.prototype.serialize = function () {
  51478. var serializationObject = {};
  51479. serializationObject.type = this.getClassName();
  51480. serializationObject.direction1 = this.direction1.asArray();
  51481. ;
  51482. serializationObject.direction2 = this.direction2.asArray();
  51483. ;
  51484. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51485. ;
  51486. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51487. ;
  51488. return serializationObject;
  51489. };
  51490. /**
  51491. * Parse properties from a JSON object
  51492. * @param serializationObject defines the JSON object
  51493. */
  51494. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51495. this.direction1.copyFrom(serializationObject.direction1);
  51496. this.direction2.copyFrom(serializationObject.direction2);
  51497. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51498. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51499. };
  51500. return BoxParticleEmitter;
  51501. }());
  51502. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51503. })(BABYLON || (BABYLON = {}));
  51504. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51505. var BABYLON;
  51506. (function (BABYLON) {
  51507. /**
  51508. * Particle emitter emitting particles from the inside of a cone.
  51509. * It emits the particles alongside the cone volume from the base to the particle.
  51510. * The emission direction might be randomized.
  51511. */
  51512. var ConeParticleEmitter = /** @class */ (function () {
  51513. /**
  51514. * Creates a new instance of @see ConeParticleEmitter
  51515. * @param radius the radius of the emission cone (1 by default)
  51516. * @param angles the cone base angle (PI by default)
  51517. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51518. */
  51519. function ConeParticleEmitter(radius,
  51520. /**
  51521. * The radius of the emission cone.
  51522. */
  51523. angle,
  51524. /**
  51525. * The cone base angle.
  51526. */
  51527. directionRandomizer) {
  51528. if (radius === void 0) { radius = 1; }
  51529. if (angle === void 0) { angle = Math.PI; }
  51530. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51531. this.angle = angle;
  51532. this.directionRandomizer = directionRandomizer;
  51533. this.radius = radius;
  51534. }
  51535. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51536. /**
  51537. * Gets the radius of the emission cone.
  51538. */
  51539. get: function () {
  51540. return this._radius;
  51541. },
  51542. /**
  51543. * Sets the radius of the emission cone.
  51544. */
  51545. set: function (value) {
  51546. this._radius = value;
  51547. if (this.angle !== 0) {
  51548. this._height = value / Math.tan(this.angle / 2);
  51549. }
  51550. else {
  51551. this._height = 1;
  51552. }
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. /**
  51558. * Called by the particle System when the direction is computed for the created particle.
  51559. * @param emitPower is the power of the particle (speed)
  51560. * @param worldMatrix is the world matrix of the particle system
  51561. * @param directionToUpdate is the direction vector to update with the result
  51562. * @param particle is the particle we are computed the direction for
  51563. */
  51564. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51565. if (this.angle === 0) {
  51566. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51567. }
  51568. else {
  51569. // measure the direction Vector from the emitter to the particle.
  51570. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51571. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51572. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51573. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51574. direction.x += randX;
  51575. direction.y += randY;
  51576. direction.z += randZ;
  51577. direction.normalize();
  51578. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51579. }
  51580. };
  51581. /**
  51582. * Called by the particle System when the position is computed for the created particle.
  51583. * @param worldMatrix is the world matrix of the particle system
  51584. * @param positionToUpdate is the position vector to update with the result
  51585. * @param particle is the particle we are computed the position for
  51586. */
  51587. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51588. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51589. var h = BABYLON.Scalar.RandomRange(0, 1);
  51590. // Better distribution in a cone at normal angles.
  51591. h = 1 - h * h;
  51592. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51593. radius = radius * h / this._height;
  51594. var randX = radius * Math.sin(s);
  51595. var randZ = radius * Math.cos(s);
  51596. var randY = h * this._height;
  51597. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51598. };
  51599. /**
  51600. * Clones the current emitter and returns a copy of it
  51601. * @returns the new emitter
  51602. */
  51603. ConeParticleEmitter.prototype.clone = function () {
  51604. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51605. BABYLON.Tools.DeepCopy(this, newOne);
  51606. return newOne;
  51607. };
  51608. /**
  51609. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51610. * @param effect defines the update shader
  51611. */
  51612. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51613. effect.setFloat("radius", this.radius);
  51614. effect.setFloat("angle", this.angle);
  51615. effect.setFloat("height", this._height);
  51616. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51617. };
  51618. /**
  51619. * Returns a string to use to update the GPU particles update shader
  51620. * @returns a string containng the defines string
  51621. */
  51622. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51623. return "#define CONEEMITTER";
  51624. };
  51625. /**
  51626. * Returns the string "BoxEmitter"
  51627. * @returns a string containing the class name
  51628. */
  51629. ConeParticleEmitter.prototype.getClassName = function () {
  51630. return "ConeEmitter";
  51631. };
  51632. /**
  51633. * Serializes the particle system to a JSON object.
  51634. * @returns the JSON object
  51635. */
  51636. ConeParticleEmitter.prototype.serialize = function () {
  51637. var serializationObject = {};
  51638. serializationObject.type = this.getClassName();
  51639. serializationObject.radius = this.radius;
  51640. serializationObject.angle = this.angle;
  51641. serializationObject.directionRandomizer = this.directionRandomizer;
  51642. return serializationObject;
  51643. };
  51644. /**
  51645. * Parse properties from a JSON object
  51646. * @param serializationObject defines the JSON object
  51647. */
  51648. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51649. this.radius = serializationObject.radius;
  51650. this.angle = serializationObject.angle;
  51651. this.directionRandomizer = serializationObject.directionRandomizer;
  51652. };
  51653. return ConeParticleEmitter;
  51654. }());
  51655. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51656. })(BABYLON || (BABYLON = {}));
  51657. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51658. var BABYLON;
  51659. (function (BABYLON) {
  51660. /**
  51661. * Particle emitter emitting particles from the inside of a sphere.
  51662. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51663. */
  51664. var SphereParticleEmitter = /** @class */ (function () {
  51665. /**
  51666. * Creates a new instance of @see SphereParticleEmitter
  51667. * @param radius the radius of the emission sphere (1 by default)
  51668. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51669. */
  51670. function SphereParticleEmitter(
  51671. /**
  51672. * The radius of the emission sphere.
  51673. */
  51674. radius,
  51675. /**
  51676. * How much to randomize the particle direction [0-1].
  51677. */
  51678. directionRandomizer) {
  51679. if (radius === void 0) { radius = 1; }
  51680. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51681. this.radius = radius;
  51682. this.directionRandomizer = directionRandomizer;
  51683. }
  51684. /**
  51685. * Called by the particle System when the direction is computed for the created particle.
  51686. * @param emitPower is the power of the particle (speed)
  51687. * @param worldMatrix is the world matrix of the particle system
  51688. * @param directionToUpdate is the direction vector to update with the result
  51689. * @param particle is the particle we are computed the direction for
  51690. */
  51691. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51692. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51693. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51694. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51695. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51696. direction.x += randX;
  51697. direction.y += randY;
  51698. direction.z += randZ;
  51699. direction.normalize();
  51700. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51701. };
  51702. /**
  51703. * Called by the particle System when the position is computed for the created particle.
  51704. * @param worldMatrix is the world matrix of the particle system
  51705. * @param positionToUpdate is the position vector to update with the result
  51706. * @param particle is the particle we are computed the position for
  51707. */
  51708. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51709. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51710. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51711. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51712. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51713. var randY = randRadius * Math.cos(theta);
  51714. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51715. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51716. };
  51717. /**
  51718. * Clones the current emitter and returns a copy of it
  51719. * @returns the new emitter
  51720. */
  51721. SphereParticleEmitter.prototype.clone = function () {
  51722. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51723. BABYLON.Tools.DeepCopy(this, newOne);
  51724. return newOne;
  51725. };
  51726. /**
  51727. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51728. * @param effect defines the update shader
  51729. */
  51730. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51731. effect.setFloat("radius", this.radius);
  51732. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51733. };
  51734. /**
  51735. * Returns a string to use to update the GPU particles update shader
  51736. * @returns a string containng the defines string
  51737. */
  51738. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51739. return "#define SPHEREEMITTER";
  51740. };
  51741. /**
  51742. * Returns the string "SphereParticleEmitter"
  51743. * @returns a string containing the class name
  51744. */
  51745. SphereParticleEmitter.prototype.getClassName = function () {
  51746. return "SphereParticleEmitter";
  51747. };
  51748. /**
  51749. * Serializes the particle system to a JSON object.
  51750. * @returns the JSON object
  51751. */
  51752. SphereParticleEmitter.prototype.serialize = function () {
  51753. var serializationObject = {};
  51754. serializationObject.type = this.getClassName();
  51755. serializationObject.radius = this.radius;
  51756. serializationObject.directionRandomizer = this.directionRandomizer;
  51757. return serializationObject;
  51758. };
  51759. /**
  51760. * Parse properties from a JSON object
  51761. * @param serializationObject defines the JSON object
  51762. */
  51763. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51764. this.radius = serializationObject.radius;
  51765. this.directionRandomizer = serializationObject.directionRandomizer;
  51766. };
  51767. return SphereParticleEmitter;
  51768. }());
  51769. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51770. /**
  51771. * Particle emitter emitting particles from the inside of a sphere.
  51772. * It emits the particles randomly between two vectors.
  51773. */
  51774. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51775. __extends(SphereDirectedParticleEmitter, _super);
  51776. /**
  51777. * Creates a new instance of @see SphereDirectedParticleEmitter
  51778. * @param radius the radius of the emission sphere (1 by default)
  51779. * @param direction1 the min limit of the emission direction (up vector by default)
  51780. * @param direction2 the max limit of the emission direction (up vector by default)
  51781. */
  51782. function SphereDirectedParticleEmitter(radius,
  51783. /**
  51784. * The min limit of the emission direction.
  51785. */
  51786. direction1,
  51787. /**
  51788. * The max limit of the emission direction.
  51789. */
  51790. direction2) {
  51791. if (radius === void 0) { radius = 1; }
  51792. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51793. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51794. var _this = _super.call(this, radius) || this;
  51795. _this.direction1 = direction1;
  51796. _this.direction2 = direction2;
  51797. return _this;
  51798. }
  51799. /**
  51800. * Called by the particle System when the direction is computed for the created particle.
  51801. * @param emitPower is the power of the particle (speed)
  51802. * @param worldMatrix is the world matrix of the particle system
  51803. * @param directionToUpdate is the direction vector to update with the result
  51804. * @param particle is the particle we are computed the direction for
  51805. */
  51806. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51807. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51808. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51809. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51810. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51811. };
  51812. /**
  51813. * Clones the current emitter and returns a copy of it
  51814. * @returns the new emitter
  51815. */
  51816. SphereDirectedParticleEmitter.prototype.clone = function () {
  51817. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51818. BABYLON.Tools.DeepCopy(this, newOne);
  51819. return newOne;
  51820. };
  51821. /**
  51822. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51823. * @param effect defines the update shader
  51824. */
  51825. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51826. effect.setFloat("radius", this.radius);
  51827. effect.setVector3("direction1", this.direction1);
  51828. effect.setVector3("direction2", this.direction2);
  51829. };
  51830. /**
  51831. * Returns a string to use to update the GPU particles update shader
  51832. * @returns a string containng the defines string
  51833. */
  51834. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51835. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51836. };
  51837. /**
  51838. * Returns the string "SphereDirectedParticleEmitter"
  51839. * @returns a string containing the class name
  51840. */
  51841. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51842. return "SphereDirectedParticleEmitter";
  51843. };
  51844. /**
  51845. * Serializes the particle system to a JSON object.
  51846. * @returns the JSON object
  51847. */
  51848. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51849. var serializationObject = _super.prototype.serialize.call(this);
  51850. ;
  51851. serializationObject.direction1 = this.direction1.asArray();
  51852. ;
  51853. serializationObject.direction2 = this.direction2.asArray();
  51854. ;
  51855. return serializationObject;
  51856. };
  51857. /**
  51858. * Parse properties from a JSON object
  51859. * @param serializationObject defines the JSON object
  51860. */
  51861. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51862. _super.prototype.parse.call(this, serializationObject);
  51863. this.direction1.copyFrom(serializationObject.direction1);
  51864. this.direction2.copyFrom(serializationObject.direction2);
  51865. };
  51866. return SphereDirectedParticleEmitter;
  51867. }(SphereParticleEmitter));
  51868. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51869. })(BABYLON || (BABYLON = {}));
  51870. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51871. var BABYLON;
  51872. (function (BABYLON) {
  51873. /**
  51874. * Represents one particle of a solid particle system.
  51875. * @see SolidParticleSystem
  51876. */
  51877. var SolidParticle = /** @class */ (function () {
  51878. /**
  51879. * Creates a Solid Particle object.
  51880. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51881. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51882. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51883. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51884. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51885. * @param shapeId (integer) is the model shape identifier in the SPS.
  51886. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51887. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51888. */
  51889. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51890. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51891. /**
  51892. * particle global index
  51893. */
  51894. this.idx = 0;
  51895. /**
  51896. * The color of the particle
  51897. */
  51898. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51899. /**
  51900. * The world space position of the particle.
  51901. */
  51902. this.position = BABYLON.Vector3.Zero();
  51903. /**
  51904. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51905. */
  51906. this.rotation = BABYLON.Vector3.Zero();
  51907. /**
  51908. * The scaling of the particle.
  51909. */
  51910. this.scaling = BABYLON.Vector3.One();
  51911. /**
  51912. * The uvs of the particle.
  51913. */
  51914. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51915. /**
  51916. * The current speed of the particle.
  51917. */
  51918. this.velocity = BABYLON.Vector3.Zero();
  51919. /**
  51920. * The pivot point in the particle local space.
  51921. */
  51922. this.pivot = BABYLON.Vector3.Zero();
  51923. /**
  51924. * Must the particle be translated from its pivot point in its local space ?
  51925. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51926. * Default : false
  51927. */
  51928. this.translateFromPivot = false;
  51929. /**
  51930. * Is the particle active or not ?
  51931. */
  51932. this.alive = true;
  51933. /**
  51934. * Is the particle visible or not ?
  51935. */
  51936. this.isVisible = true;
  51937. /**
  51938. * Index of this particle in the global "positions" array (Internal use)
  51939. */
  51940. this._pos = 0;
  51941. /**
  51942. * Index of this particle in the global "indices" array (Internal use)
  51943. */
  51944. this._ind = 0;
  51945. /**
  51946. * ModelShape id of this particle
  51947. */
  51948. this.shapeId = 0;
  51949. /**
  51950. * Index of the particle in its shape id (Internal use)
  51951. */
  51952. this.idxInShape = 0;
  51953. /**
  51954. * Still set as invisible in order to skip useless computations (Internal use)
  51955. */
  51956. this._stillInvisible = false;
  51957. /**
  51958. * Last computed particle rotation matrix
  51959. */
  51960. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51961. /**
  51962. * Parent particle Id, if any.
  51963. * Default null.
  51964. */
  51965. this.parentId = null;
  51966. /**
  51967. * Internal global position in the SPS.
  51968. */
  51969. this._globalPosition = BABYLON.Vector3.Zero();
  51970. this.idx = particleIndex;
  51971. this._pos = positionIndex;
  51972. this._ind = indiceIndex;
  51973. this._model = model;
  51974. this.shapeId = shapeId;
  51975. this.idxInShape = idxInShape;
  51976. this._sps = sps;
  51977. if (modelBoundingInfo) {
  51978. this._modelBoundingInfo = modelBoundingInfo;
  51979. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51980. }
  51981. }
  51982. Object.defineProperty(SolidParticle.prototype, "scale", {
  51983. /**
  51984. * Legacy support, changed scale to scaling
  51985. */
  51986. get: function () {
  51987. return this.scaling;
  51988. },
  51989. /**
  51990. * Legacy support, changed scale to scaling
  51991. */
  51992. set: function (scale) {
  51993. this.scaling = scale;
  51994. },
  51995. enumerable: true,
  51996. configurable: true
  51997. });
  51998. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51999. /**
  52000. * Legacy support, changed quaternion to rotationQuaternion
  52001. */
  52002. get: function () {
  52003. return this.rotationQuaternion;
  52004. },
  52005. /**
  52006. * Legacy support, changed quaternion to rotationQuaternion
  52007. */
  52008. set: function (q) {
  52009. this.rotationQuaternion = q;
  52010. },
  52011. enumerable: true,
  52012. configurable: true
  52013. });
  52014. /**
  52015. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52016. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52017. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52018. * @returns true if it intersects
  52019. */
  52020. SolidParticle.prototype.intersectsMesh = function (target) {
  52021. if (!this._boundingInfo || !target._boundingInfo) {
  52022. return false;
  52023. }
  52024. if (this._sps._bSphereOnly) {
  52025. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52026. }
  52027. return this._boundingInfo.intersects(target._boundingInfo, false);
  52028. };
  52029. return SolidParticle;
  52030. }());
  52031. BABYLON.SolidParticle = SolidParticle;
  52032. /**
  52033. * Represents the shape of the model used by one particle of a solid particle system.
  52034. * SPS internal tool, don't use it manually.
  52035. * @see SolidParticleSystem
  52036. */
  52037. var ModelShape = /** @class */ (function () {
  52038. /**
  52039. * 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.
  52040. * SPS internal tool, don't use it manually.
  52041. * @ignore
  52042. */
  52043. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52044. /**
  52045. * length of the shape in the model indices array (internal use)
  52046. */
  52047. this._indicesLength = 0;
  52048. this.shapeID = id;
  52049. this._shape = shape;
  52050. this._indicesLength = indicesLength;
  52051. this._shapeUV = shapeUV;
  52052. this._positionFunction = posFunction;
  52053. this._vertexFunction = vtxFunction;
  52054. }
  52055. return ModelShape;
  52056. }());
  52057. BABYLON.ModelShape = ModelShape;
  52058. /**
  52059. * Represents a Depth Sorted Particle in the solid particle system.
  52060. * @see SolidParticleSystem
  52061. */
  52062. var DepthSortedParticle = /** @class */ (function () {
  52063. function DepthSortedParticle() {
  52064. /**
  52065. * Index of the particle in the "indices" array
  52066. */
  52067. this.ind = 0;
  52068. /**
  52069. * Length of the particle shape in the "indices" array
  52070. */
  52071. this.indicesLength = 0;
  52072. /**
  52073. * Squared distance from the particle to the camera
  52074. */
  52075. this.sqDistance = 0.0;
  52076. }
  52077. return DepthSortedParticle;
  52078. }());
  52079. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52080. })(BABYLON || (BABYLON = {}));
  52081. //# sourceMappingURL=babylon.solidParticle.js.map
  52082. var BABYLON;
  52083. (function (BABYLON) {
  52084. /**
  52085. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52086. *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.
  52087. * The SPS is also a particle system. It provides some methods to manage the particles.
  52088. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52089. *
  52090. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52091. */
  52092. var SolidParticleSystem = /** @class */ (function () {
  52093. /**
  52094. * Creates a SPS (Solid Particle System) object.
  52095. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52096. * @param scene (Scene) is the scene in which the SPS is added.
  52097. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52098. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52099. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52100. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52101. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52102. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52103. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52104. */
  52105. function SolidParticleSystem(name, scene, options) {
  52106. /**
  52107. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52108. * Example : var p = SPS.particles[i];
  52109. */
  52110. this.particles = new Array();
  52111. /**
  52112. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52113. */
  52114. this.nbParticles = 0;
  52115. /**
  52116. * If the particles must ever face the camera (default false). Useful for planar particles.
  52117. */
  52118. this.billboard = false;
  52119. /**
  52120. * Recompute normals when adding a shape
  52121. */
  52122. this.recomputeNormals = true;
  52123. /**
  52124. * This a counter ofr your own usage. It's not set by any SPS functions.
  52125. */
  52126. this.counter = 0;
  52127. /**
  52128. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52129. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52130. */
  52131. this.vars = {};
  52132. /**
  52133. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52134. */
  52135. this._bSphereOnly = false;
  52136. /**
  52137. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52138. */
  52139. this._bSphereRadiusFactor = 1.0;
  52140. this._positions = new Array();
  52141. this._indices = new Array();
  52142. this._normals = new Array();
  52143. this._colors = new Array();
  52144. this._uvs = new Array();
  52145. this._index = 0; // indices index
  52146. this._updatable = true;
  52147. this._pickable = false;
  52148. this._isVisibilityBoxLocked = false;
  52149. this._alwaysVisible = false;
  52150. this._depthSort = false;
  52151. this._shapeCounter = 0;
  52152. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52153. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52154. this._computeParticleColor = true;
  52155. this._computeParticleTexture = true;
  52156. this._computeParticleRotation = true;
  52157. this._computeParticleVertex = false;
  52158. this._computeBoundingBox = false;
  52159. this._depthSortParticles = true;
  52160. this._cam_axisZ = BABYLON.Vector3.Zero();
  52161. this._cam_axisY = BABYLON.Vector3.Zero();
  52162. this._cam_axisX = BABYLON.Vector3.Zero();
  52163. this._axisZ = BABYLON.Axis.Z;
  52164. this._camDir = BABYLON.Vector3.Zero();
  52165. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52166. this._rotMatrix = new BABYLON.Matrix();
  52167. this._invertMatrix = new BABYLON.Matrix();
  52168. this._rotated = BABYLON.Vector3.Zero();
  52169. this._quaternion = new BABYLON.Quaternion();
  52170. this._vertex = BABYLON.Vector3.Zero();
  52171. this._normal = BABYLON.Vector3.Zero();
  52172. this._yaw = 0.0;
  52173. this._pitch = 0.0;
  52174. this._roll = 0.0;
  52175. this._halfroll = 0.0;
  52176. this._halfpitch = 0.0;
  52177. this._halfyaw = 0.0;
  52178. this._sinRoll = 0.0;
  52179. this._cosRoll = 0.0;
  52180. this._sinPitch = 0.0;
  52181. this._cosPitch = 0.0;
  52182. this._sinYaw = 0.0;
  52183. this._cosYaw = 0.0;
  52184. this._mustUnrotateFixedNormals = false;
  52185. this._minimum = BABYLON.Vector3.Zero();
  52186. this._maximum = BABYLON.Vector3.Zero();
  52187. this._minBbox = BABYLON.Vector3.Zero();
  52188. this._maxBbox = BABYLON.Vector3.Zero();
  52189. this._particlesIntersect = false;
  52190. this._depthSortFunction = function (p1, p2) {
  52191. return (p2.sqDistance - p1.sqDistance);
  52192. };
  52193. this._needs32Bits = false;
  52194. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52195. this._scaledPivot = BABYLON.Vector3.Zero();
  52196. this._particleHasParent = false;
  52197. this.name = name;
  52198. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52199. this._camera = scene.activeCamera;
  52200. this._pickable = options ? options.isPickable : false;
  52201. this._depthSort = options ? options.enableDepthSort : false;
  52202. this._particlesIntersect = options ? options.particleIntersection : false;
  52203. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52204. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52205. if (options && options.updatable) {
  52206. this._updatable = options.updatable;
  52207. }
  52208. else {
  52209. this._updatable = true;
  52210. }
  52211. if (this._pickable) {
  52212. this.pickedParticles = [];
  52213. }
  52214. if (this._depthSort) {
  52215. this.depthSortedParticles = [];
  52216. }
  52217. }
  52218. /**
  52219. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52220. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52221. * @returns the created mesh
  52222. */
  52223. SolidParticleSystem.prototype.buildMesh = function () {
  52224. if (this.nbParticles === 0) {
  52225. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52226. this.addShape(triangle, 1);
  52227. triangle.dispose();
  52228. }
  52229. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52230. this._positions32 = new Float32Array(this._positions);
  52231. this._uvs32 = new Float32Array(this._uvs);
  52232. this._colors32 = new Float32Array(this._colors);
  52233. if (this.recomputeNormals) {
  52234. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52235. }
  52236. this._normals32 = new Float32Array(this._normals);
  52237. this._fixedNormal32 = new Float32Array(this._normals);
  52238. if (this._mustUnrotateFixedNormals) {
  52239. this._unrotateFixedNormals();
  52240. }
  52241. var vertexData = new BABYLON.VertexData();
  52242. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52243. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52244. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52245. if (this._uvs32) {
  52246. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52247. ;
  52248. }
  52249. if (this._colors32) {
  52250. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52251. }
  52252. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52253. vertexData.applyToMesh(mesh, this._updatable);
  52254. this.mesh = mesh;
  52255. this.mesh.isPickable = this._pickable;
  52256. // free memory
  52257. if (!this._depthSort) {
  52258. this._indices = null;
  52259. }
  52260. this._positions = null;
  52261. this._normals = null;
  52262. this._uvs = null;
  52263. this._colors = null;
  52264. if (!this._updatable) {
  52265. this.particles.length = 0;
  52266. }
  52267. return mesh;
  52268. };
  52269. /**
  52270. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52271. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52272. * Thus the particles generated from `digest()` have their property `position` set yet.
  52273. * @param mesh ( Mesh ) is the mesh to be digested
  52274. * @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
  52275. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52276. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52277. * @returns the current SPS
  52278. */
  52279. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52280. var size = (options && options.facetNb) || 1;
  52281. var number = (options && options.number) || 0;
  52282. var delta = (options && options.delta) || 0;
  52283. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52284. var meshInd = mesh.getIndices();
  52285. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52286. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52287. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52288. var f = 0; // facet counter
  52289. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52290. // compute size from number
  52291. if (number) {
  52292. number = (number > totalFacets) ? totalFacets : number;
  52293. size = Math.round(totalFacets / number);
  52294. delta = 0;
  52295. }
  52296. else {
  52297. size = (size > totalFacets) ? totalFacets : size;
  52298. }
  52299. var facetPos = []; // submesh positions
  52300. var facetInd = []; // submesh indices
  52301. var facetUV = []; // submesh UV
  52302. var facetCol = []; // submesh colors
  52303. var barycenter = BABYLON.Vector3.Zero();
  52304. var sizeO = size;
  52305. while (f < totalFacets) {
  52306. size = sizeO + Math.floor((1 + delta) * Math.random());
  52307. if (f > totalFacets - size) {
  52308. size = totalFacets - f;
  52309. }
  52310. // reset temp arrays
  52311. facetPos.length = 0;
  52312. facetInd.length = 0;
  52313. facetUV.length = 0;
  52314. facetCol.length = 0;
  52315. // iterate over "size" facets
  52316. var fi = 0;
  52317. for (var j = f * 3; j < (f + size) * 3; j++) {
  52318. facetInd.push(fi);
  52319. var i = meshInd[j];
  52320. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52321. if (meshUV) {
  52322. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52323. }
  52324. if (meshCol) {
  52325. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52326. }
  52327. fi++;
  52328. }
  52329. // create a model shape for each single particle
  52330. var idx = this.nbParticles;
  52331. var shape = this._posToShape(facetPos);
  52332. var shapeUV = this._uvsToShapeUV(facetUV);
  52333. // compute the barycenter of the shape
  52334. var v;
  52335. for (v = 0; v < shape.length; v++) {
  52336. barycenter.addInPlace(shape[v]);
  52337. }
  52338. barycenter.scaleInPlace(1 / shape.length);
  52339. // shift the shape from its barycenter to the origin
  52340. for (v = 0; v < shape.length; v++) {
  52341. shape[v].subtractInPlace(barycenter);
  52342. }
  52343. var bInfo;
  52344. if (this._particlesIntersect) {
  52345. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52346. }
  52347. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52348. // add the particle in the SPS
  52349. var currentPos = this._positions.length;
  52350. var currentInd = this._indices.length;
  52351. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52352. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52353. // initialize the particle position
  52354. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52355. this._index += shape.length;
  52356. idx++;
  52357. this.nbParticles++;
  52358. this._shapeCounter++;
  52359. f += size;
  52360. }
  52361. return this;
  52362. };
  52363. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52364. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52365. var index = 0;
  52366. var idx = 0;
  52367. for (var p = 0; p < this.particles.length; p++) {
  52368. this._particle = this.particles[p];
  52369. this._shape = this._particle._model._shape;
  52370. if (this._particle.rotationQuaternion) {
  52371. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52372. }
  52373. else {
  52374. this._yaw = this._particle.rotation.y;
  52375. this._pitch = this._particle.rotation.x;
  52376. this._roll = this._particle.rotation.z;
  52377. this._quaternionRotationYPR();
  52378. }
  52379. this._quaternionToRotationMatrix();
  52380. this._rotMatrix.invertToRef(this._invertMatrix);
  52381. for (var pt = 0; pt < this._shape.length; pt++) {
  52382. idx = index + pt * 3;
  52383. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52384. this._fixedNormal32[idx] = this._normal.x;
  52385. this._fixedNormal32[idx + 1] = this._normal.y;
  52386. this._fixedNormal32[idx + 2] = this._normal.z;
  52387. }
  52388. index = idx + 3;
  52389. }
  52390. };
  52391. //reset copy
  52392. SolidParticleSystem.prototype._resetCopy = function () {
  52393. this._copy.position.x = 0;
  52394. this._copy.position.y = 0;
  52395. this._copy.position.z = 0;
  52396. this._copy.rotation.x = 0;
  52397. this._copy.rotation.y = 0;
  52398. this._copy.rotation.z = 0;
  52399. this._copy.rotationQuaternion = null;
  52400. this._copy.scaling.x = 1.0;
  52401. this._copy.scaling.y = 1.0;
  52402. this._copy.scaling.z = 1.0;
  52403. this._copy.uvs.x = 0;
  52404. this._copy.uvs.y = 0;
  52405. this._copy.uvs.z = 1.0;
  52406. this._copy.uvs.w = 1.0;
  52407. this._copy.color = null;
  52408. this._copy.translateFromPivot = false;
  52409. };
  52410. // _meshBuilder : inserts the shape model in the global SPS mesh
  52411. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52412. var i;
  52413. var u = 0;
  52414. var c = 0;
  52415. var n = 0;
  52416. this._resetCopy();
  52417. if (options && options.positionFunction) {
  52418. options.positionFunction(this._copy, idx, idxInShape);
  52419. this._mustUnrotateFixedNormals = true;
  52420. }
  52421. if (this._copy.rotationQuaternion) {
  52422. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52423. }
  52424. else {
  52425. this._yaw = this._copy.rotation.y;
  52426. this._pitch = this._copy.rotation.x;
  52427. this._roll = this._copy.rotation.z;
  52428. this._quaternionRotationYPR();
  52429. }
  52430. this._quaternionToRotationMatrix();
  52431. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52432. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52433. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52434. if (this._copy.translateFromPivot) {
  52435. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52436. }
  52437. else {
  52438. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52439. }
  52440. for (i = 0; i < shape.length; i++) {
  52441. this._vertex.x = shape[i].x;
  52442. this._vertex.y = shape[i].y;
  52443. this._vertex.z = shape[i].z;
  52444. if (options && options.vertexFunction) {
  52445. options.vertexFunction(this._copy, this._vertex, i);
  52446. }
  52447. this._vertex.x *= this._copy.scaling.x;
  52448. this._vertex.y *= this._copy.scaling.y;
  52449. this._vertex.z *= this._copy.scaling.z;
  52450. this._vertex.x -= this._scaledPivot.x;
  52451. this._vertex.y -= this._scaledPivot.y;
  52452. this._vertex.z -= this._scaledPivot.z;
  52453. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52454. this._rotated.addInPlace(this._pivotBackTranslation);
  52455. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52456. if (meshUV) {
  52457. 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);
  52458. u += 2;
  52459. }
  52460. if (this._copy.color) {
  52461. this._color = this._copy.color;
  52462. }
  52463. else if (meshCol && meshCol[c] !== undefined) {
  52464. this._color.r = meshCol[c];
  52465. this._color.g = meshCol[c + 1];
  52466. this._color.b = meshCol[c + 2];
  52467. this._color.a = meshCol[c + 3];
  52468. }
  52469. else {
  52470. this._color.r = 1.0;
  52471. this._color.g = 1.0;
  52472. this._color.b = 1.0;
  52473. this._color.a = 1.0;
  52474. }
  52475. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52476. c += 4;
  52477. if (!this.recomputeNormals && meshNor) {
  52478. this._normal.x = meshNor[n];
  52479. this._normal.y = meshNor[n + 1];
  52480. this._normal.z = meshNor[n + 2];
  52481. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52482. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52483. n += 3;
  52484. }
  52485. }
  52486. for (i = 0; i < meshInd.length; i++) {
  52487. var current_ind = p + meshInd[i];
  52488. indices.push(current_ind);
  52489. if (current_ind > 65535) {
  52490. this._needs32Bits = true;
  52491. }
  52492. }
  52493. if (this._pickable) {
  52494. var nbfaces = meshInd.length / 3;
  52495. for (i = 0; i < nbfaces; i++) {
  52496. this.pickedParticles.push({ idx: idx, faceId: i });
  52497. }
  52498. }
  52499. if (this._depthSort) {
  52500. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52501. }
  52502. return this._copy;
  52503. };
  52504. // returns a shape array from positions array
  52505. SolidParticleSystem.prototype._posToShape = function (positions) {
  52506. var shape = [];
  52507. for (var i = 0; i < positions.length; i += 3) {
  52508. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52509. }
  52510. return shape;
  52511. };
  52512. // returns a shapeUV array from a Vector4 uvs
  52513. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52514. var shapeUV = [];
  52515. if (uvs) {
  52516. for (var i = 0; i < uvs.length; i++)
  52517. shapeUV.push(uvs[i]);
  52518. }
  52519. return shapeUV;
  52520. };
  52521. // adds a new particle object in the particles array
  52522. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52523. if (bInfo === void 0) { bInfo = null; }
  52524. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52525. this.particles.push(sp);
  52526. return sp;
  52527. };
  52528. /**
  52529. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52530. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52531. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52532. * @param nb (positive integer) the number of particles to be created from this model
  52533. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52534. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52535. * @returns the number of shapes in the system
  52536. */
  52537. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52538. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52539. var meshInd = mesh.getIndices();
  52540. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52541. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52542. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52543. var bbInfo;
  52544. if (this._particlesIntersect) {
  52545. bbInfo = mesh.getBoundingInfo();
  52546. }
  52547. var shape = this._posToShape(meshPos);
  52548. var shapeUV = this._uvsToShapeUV(meshUV);
  52549. var posfunc = options ? options.positionFunction : null;
  52550. var vtxfunc = options ? options.vertexFunction : null;
  52551. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52552. // particles
  52553. var sp;
  52554. var currentCopy;
  52555. var idx = this.nbParticles;
  52556. for (var i = 0; i < nb; i++) {
  52557. var currentPos = this._positions.length;
  52558. var currentInd = this._indices.length;
  52559. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52560. if (this._updatable) {
  52561. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52562. sp.position.copyFrom(currentCopy.position);
  52563. sp.rotation.copyFrom(currentCopy.rotation);
  52564. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52565. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52566. }
  52567. if (currentCopy.color && sp.color) {
  52568. sp.color.copyFrom(currentCopy.color);
  52569. }
  52570. sp.scaling.copyFrom(currentCopy.scaling);
  52571. sp.uvs.copyFrom(currentCopy.uvs);
  52572. }
  52573. this._index += shape.length;
  52574. idx++;
  52575. }
  52576. this.nbParticles += nb;
  52577. this._shapeCounter++;
  52578. return this._shapeCounter - 1;
  52579. };
  52580. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52581. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52582. this._resetCopy();
  52583. if (particle._model._positionFunction) {
  52584. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52585. }
  52586. if (this._copy.rotationQuaternion) {
  52587. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52588. }
  52589. else {
  52590. this._yaw = this._copy.rotation.y;
  52591. this._pitch = this._copy.rotation.x;
  52592. this._roll = this._copy.rotation.z;
  52593. this._quaternionRotationYPR();
  52594. }
  52595. this._quaternionToRotationMatrix();
  52596. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52597. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52598. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52599. if (this._copy.translateFromPivot) {
  52600. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52601. }
  52602. else {
  52603. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52604. }
  52605. this._shape = particle._model._shape;
  52606. for (var pt = 0; pt < this._shape.length; pt++) {
  52607. this._vertex.x = this._shape[pt].x;
  52608. this._vertex.y = this._shape[pt].y;
  52609. this._vertex.z = this._shape[pt].z;
  52610. if (particle._model._vertexFunction) {
  52611. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52612. }
  52613. this._vertex.x *= this._copy.scaling.x;
  52614. this._vertex.y *= this._copy.scaling.y;
  52615. this._vertex.z *= this._copy.scaling.z;
  52616. this._vertex.x -= this._scaledPivot.x;
  52617. this._vertex.y -= this._scaledPivot.y;
  52618. this._vertex.z -= this._scaledPivot.z;
  52619. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52620. this._rotated.addInPlace(this._pivotBackTranslation);
  52621. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52622. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52623. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52624. }
  52625. particle.position.x = 0.0;
  52626. particle.position.y = 0.0;
  52627. particle.position.z = 0.0;
  52628. particle.rotation.x = 0.0;
  52629. particle.rotation.y = 0.0;
  52630. particle.rotation.z = 0.0;
  52631. particle.rotationQuaternion = null;
  52632. particle.scaling.x = 1.0;
  52633. particle.scaling.y = 1.0;
  52634. particle.scaling.z = 1.0;
  52635. particle.uvs.x = 0.0;
  52636. particle.uvs.y = 0.0;
  52637. particle.uvs.z = 1.0;
  52638. particle.uvs.w = 1.0;
  52639. particle.pivot.x = 0.0;
  52640. particle.pivot.y = 0.0;
  52641. particle.pivot.z = 0.0;
  52642. particle.translateFromPivot = false;
  52643. particle.parentId = null;
  52644. };
  52645. /**
  52646. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52647. * @returns the SPS.
  52648. */
  52649. SolidParticleSystem.prototype.rebuildMesh = function () {
  52650. for (var p = 0; p < this.particles.length; p++) {
  52651. this._rebuildParticle(this.particles[p]);
  52652. }
  52653. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52654. return this;
  52655. };
  52656. /**
  52657. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52658. * This method calls `updateParticle()` for each particle of the SPS.
  52659. * For an animated SPS, it is usually called within the render loop.
  52660. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52661. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52662. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52663. * @returns the SPS.
  52664. */
  52665. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52666. if (start === void 0) { start = 0; }
  52667. if (end === void 0) { end = this.nbParticles - 1; }
  52668. if (update === void 0) { update = true; }
  52669. if (!this._updatable) {
  52670. return this;
  52671. }
  52672. // custom beforeUpdate
  52673. this.beforeUpdateParticles(start, end, update);
  52674. this._cam_axisX.x = 1.0;
  52675. this._cam_axisX.y = 0.0;
  52676. this._cam_axisX.z = 0.0;
  52677. this._cam_axisY.x = 0.0;
  52678. this._cam_axisY.y = 1.0;
  52679. this._cam_axisY.z = 0.0;
  52680. this._cam_axisZ.x = 0.0;
  52681. this._cam_axisZ.y = 0.0;
  52682. this._cam_axisZ.z = 1.0;
  52683. // cases when the World Matrix is to be computed first
  52684. if (this.billboard || this._depthSort) {
  52685. this.mesh.computeWorldMatrix(true);
  52686. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52687. }
  52688. // if the particles will always face the camera
  52689. if (this.billboard) {
  52690. // compute the camera position and un-rotate it by the current mesh rotation
  52691. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52692. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52693. this._cam_axisZ.normalize();
  52694. // same for camera up vector extracted from the cam view matrix
  52695. var view = this._camera.getViewMatrix(true);
  52696. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52697. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52698. this._cam_axisY.normalize();
  52699. this._cam_axisX.normalize();
  52700. }
  52701. // if depthSort, compute the camera global position in the mesh local system
  52702. if (this._depthSort) {
  52703. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52704. }
  52705. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52706. var idx = 0; // current position index in the global array positions32
  52707. var index = 0; // position start index in the global array positions32 of the current particle
  52708. var colidx = 0; // current color index in the global array colors32
  52709. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52710. var uvidx = 0; // current uv index in the global array uvs32
  52711. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52712. var pt = 0; // current index in the particle model shape
  52713. if (this.mesh.isFacetDataEnabled) {
  52714. this._computeBoundingBox = true;
  52715. }
  52716. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52717. if (this._computeBoundingBox) {
  52718. if (start == 0 && end == this.nbParticles - 1) {
  52719. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52720. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52721. }
  52722. else {
  52723. if (this.mesh._boundingInfo) {
  52724. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52725. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52726. }
  52727. }
  52728. }
  52729. // particle loop
  52730. index = this.particles[start]._pos;
  52731. var vpos = (index / 3) | 0;
  52732. colorIndex = vpos * 4;
  52733. uvIndex = vpos * 2;
  52734. for (var p = start; p <= end; p++) {
  52735. this._particle = this.particles[p];
  52736. this._shape = this._particle._model._shape;
  52737. this._shapeUV = this._particle._model._shapeUV;
  52738. // call to custom user function to update the particle properties
  52739. this.updateParticle(this._particle);
  52740. // camera-particle distance for depth sorting
  52741. if (this._depthSort && this._depthSortParticles) {
  52742. var dsp = this.depthSortedParticles[p];
  52743. dsp.ind = this._particle._ind;
  52744. dsp.indicesLength = this._particle._model._indicesLength;
  52745. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52746. }
  52747. // skip the computations for inactive or already invisible particles
  52748. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52749. // increment indexes for the next particle
  52750. pt = this._shape.length;
  52751. index += pt * 3;
  52752. colorIndex += pt * 4;
  52753. uvIndex += pt * 2;
  52754. continue;
  52755. }
  52756. if (this._particle.isVisible) {
  52757. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52758. this._particleHasParent = (this._particle.parentId !== null);
  52759. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52760. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52761. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52762. // particle rotation matrix
  52763. if (this.billboard) {
  52764. this._particle.rotation.x = 0.0;
  52765. this._particle.rotation.y = 0.0;
  52766. }
  52767. if (this._computeParticleRotation || this.billboard) {
  52768. if (this._particle.rotationQuaternion) {
  52769. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52770. }
  52771. else {
  52772. this._yaw = this._particle.rotation.y;
  52773. this._pitch = this._particle.rotation.x;
  52774. this._roll = this._particle.rotation.z;
  52775. this._quaternionRotationYPR();
  52776. }
  52777. this._quaternionToRotationMatrix();
  52778. }
  52779. if (this._particleHasParent) {
  52780. this._parent = this.particles[this._particle.parentId];
  52781. 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];
  52782. 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];
  52783. 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];
  52784. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52785. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52786. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52787. if (this._computeParticleRotation || this.billboard) {
  52788. 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];
  52789. 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];
  52790. 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];
  52791. 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];
  52792. 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];
  52793. 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];
  52794. 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];
  52795. 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];
  52796. 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];
  52797. }
  52798. }
  52799. else {
  52800. this._particle._globalPosition.x = this._particle.position.x;
  52801. this._particle._globalPosition.y = this._particle.position.y;
  52802. this._particle._globalPosition.z = this._particle.position.z;
  52803. if (this._computeParticleRotation || this.billboard) {
  52804. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52805. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52806. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52807. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52808. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52809. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52810. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52811. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52812. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52813. }
  52814. }
  52815. if (this._particle.translateFromPivot) {
  52816. this._pivotBackTranslation.x = 0.0;
  52817. this._pivotBackTranslation.y = 0.0;
  52818. this._pivotBackTranslation.z = 0.0;
  52819. }
  52820. else {
  52821. this._pivotBackTranslation.x = this._scaledPivot.x;
  52822. this._pivotBackTranslation.y = this._scaledPivot.y;
  52823. this._pivotBackTranslation.z = this._scaledPivot.z;
  52824. }
  52825. // particle vertex loop
  52826. for (pt = 0; pt < this._shape.length; pt++) {
  52827. idx = index + pt * 3;
  52828. colidx = colorIndex + pt * 4;
  52829. uvidx = uvIndex + pt * 2;
  52830. this._vertex.x = this._shape[pt].x;
  52831. this._vertex.y = this._shape[pt].y;
  52832. this._vertex.z = this._shape[pt].z;
  52833. if (this._computeParticleVertex) {
  52834. this.updateParticleVertex(this._particle, this._vertex, pt);
  52835. }
  52836. // positions
  52837. this._vertex.x *= this._particle.scaling.x;
  52838. this._vertex.y *= this._particle.scaling.y;
  52839. this._vertex.z *= this._particle.scaling.z;
  52840. this._vertex.x -= this._scaledPivot.x;
  52841. this._vertex.y -= this._scaledPivot.y;
  52842. this._vertex.z -= this._scaledPivot.z;
  52843. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52844. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52845. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52846. this._rotated.x += this._pivotBackTranslation.x;
  52847. this._rotated.y += this._pivotBackTranslation.y;
  52848. this._rotated.z += this._pivotBackTranslation.z;
  52849. 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;
  52850. 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;
  52851. 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;
  52852. if (this._computeBoundingBox) {
  52853. if (this._positions32[idx] < this._minimum.x) {
  52854. this._minimum.x = this._positions32[idx];
  52855. }
  52856. if (this._positions32[idx] > this._maximum.x) {
  52857. this._maximum.x = this._positions32[idx];
  52858. }
  52859. if (this._positions32[idx + 1] < this._minimum.y) {
  52860. this._minimum.y = this._positions32[idx + 1];
  52861. }
  52862. if (this._positions32[idx + 1] > this._maximum.y) {
  52863. this._maximum.y = this._positions32[idx + 1];
  52864. }
  52865. if (this._positions32[idx + 2] < this._minimum.z) {
  52866. this._minimum.z = this._positions32[idx + 2];
  52867. }
  52868. if (this._positions32[idx + 2] > this._maximum.z) {
  52869. this._maximum.z = this._positions32[idx + 2];
  52870. }
  52871. }
  52872. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52873. if (!this._computeParticleVertex) {
  52874. this._normal.x = this._fixedNormal32[idx];
  52875. this._normal.y = this._fixedNormal32[idx + 1];
  52876. this._normal.z = this._fixedNormal32[idx + 2];
  52877. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52878. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52879. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52880. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52881. 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;
  52882. 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;
  52883. }
  52884. if (this._computeParticleColor && this._particle.color) {
  52885. this._colors32[colidx] = this._particle.color.r;
  52886. this._colors32[colidx + 1] = this._particle.color.g;
  52887. this._colors32[colidx + 2] = this._particle.color.b;
  52888. this._colors32[colidx + 3] = this._particle.color.a;
  52889. }
  52890. if (this._computeParticleTexture) {
  52891. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52892. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52893. }
  52894. }
  52895. }
  52896. else {
  52897. this._particle._stillInvisible = true; // mark the particle as invisible
  52898. for (pt = 0; pt < this._shape.length; pt++) {
  52899. idx = index + pt * 3;
  52900. colidx = colorIndex + pt * 4;
  52901. uvidx = uvIndex + pt * 2;
  52902. this._positions32[idx] = 0.0;
  52903. this._positions32[idx + 1] = 0.0;
  52904. this._positions32[idx + 2] = 0.0;
  52905. this._normals32[idx] = 0.0;
  52906. this._normals32[idx + 1] = 0.0;
  52907. this._normals32[idx + 2] = 0.0;
  52908. if (this._computeParticleColor && this._particle.color) {
  52909. this._colors32[colidx] = this._particle.color.r;
  52910. this._colors32[colidx + 1] = this._particle.color.g;
  52911. this._colors32[colidx + 2] = this._particle.color.b;
  52912. this._colors32[colidx + 3] = this._particle.color.a;
  52913. }
  52914. if (this._computeParticleTexture) {
  52915. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52916. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52917. }
  52918. }
  52919. }
  52920. // if the particle intersections must be computed : update the bbInfo
  52921. if (this._particlesIntersect) {
  52922. var bInfo = this._particle._boundingInfo;
  52923. var bBox = bInfo.boundingBox;
  52924. var bSphere = bInfo.boundingSphere;
  52925. if (!this._bSphereOnly) {
  52926. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52927. for (var b = 0; b < bBox.vectors.length; b++) {
  52928. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52929. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52930. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52931. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52932. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52933. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52934. 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;
  52935. 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;
  52936. 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;
  52937. }
  52938. bBox._update(this.mesh._worldMatrix);
  52939. }
  52940. // place and scale the particle bouding sphere in the SPS local system, then update it
  52941. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52942. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52943. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52944. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52945. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52946. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52947. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52948. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52949. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52950. 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));
  52951. bSphere._update(this.mesh._worldMatrix);
  52952. }
  52953. // increment indexes for the next particle
  52954. index = idx + 3;
  52955. colorIndex = colidx + 4;
  52956. uvIndex = uvidx + 2;
  52957. }
  52958. // if the VBO must be updated
  52959. if (update) {
  52960. if (this._computeParticleColor) {
  52961. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52962. }
  52963. if (this._computeParticleTexture) {
  52964. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52965. }
  52966. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52967. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52968. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52969. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52970. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52971. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52972. for (var i = 0; i < this._normals32.length; i++) {
  52973. this._fixedNormal32[i] = this._normals32[i];
  52974. }
  52975. }
  52976. if (!this.mesh.areNormalsFrozen) {
  52977. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52978. }
  52979. }
  52980. if (this._depthSort && this._depthSortParticles) {
  52981. this.depthSortedParticles.sort(this._depthSortFunction);
  52982. var dspl = this.depthSortedParticles.length;
  52983. var sorted = 0;
  52984. var lind = 0;
  52985. var sind = 0;
  52986. var sid = 0;
  52987. for (sorted = 0; sorted < dspl; sorted++) {
  52988. lind = this.depthSortedParticles[sorted].indicesLength;
  52989. sind = this.depthSortedParticles[sorted].ind;
  52990. for (var i = 0; i < lind; i++) {
  52991. this._indices32[sid] = this._indices[sind + i];
  52992. sid++;
  52993. }
  52994. }
  52995. this.mesh.updateIndices(this._indices32);
  52996. }
  52997. }
  52998. if (this._computeBoundingBox) {
  52999. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53000. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53001. }
  53002. this.afterUpdateParticles(start, end, update);
  53003. return this;
  53004. };
  53005. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53006. this._halfroll = this._roll * 0.5;
  53007. this._halfpitch = this._pitch * 0.5;
  53008. this._halfyaw = this._yaw * 0.5;
  53009. this._sinRoll = Math.sin(this._halfroll);
  53010. this._cosRoll = Math.cos(this._halfroll);
  53011. this._sinPitch = Math.sin(this._halfpitch);
  53012. this._cosPitch = Math.cos(this._halfpitch);
  53013. this._sinYaw = Math.sin(this._halfyaw);
  53014. this._cosYaw = Math.cos(this._halfyaw);
  53015. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53016. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53017. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53018. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53019. };
  53020. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53021. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53022. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53023. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53024. this._rotMatrix.m[3] = 0;
  53025. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53026. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53027. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53028. this._rotMatrix.m[7] = 0;
  53029. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53030. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53031. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53032. this._rotMatrix.m[11] = 0;
  53033. this._rotMatrix.m[12] = 0;
  53034. this._rotMatrix.m[13] = 0;
  53035. this._rotMatrix.m[14] = 0;
  53036. this._rotMatrix.m[15] = 1.0;
  53037. };
  53038. /**
  53039. * Disposes the SPS.
  53040. */
  53041. SolidParticleSystem.prototype.dispose = function () {
  53042. this.mesh.dispose();
  53043. this.vars = null;
  53044. // drop references to internal big arrays for the GC
  53045. this._positions = null;
  53046. this._indices = null;
  53047. this._normals = null;
  53048. this._uvs = null;
  53049. this._colors = null;
  53050. this._indices32 = null;
  53051. this._positions32 = null;
  53052. this._normals32 = null;
  53053. this._fixedNormal32 = null;
  53054. this._uvs32 = null;
  53055. this._colors32 = null;
  53056. this.pickedParticles = null;
  53057. };
  53058. /**
  53059. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53060. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53061. * @returns the SPS.
  53062. */
  53063. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53064. if (!this._isVisibilityBoxLocked) {
  53065. this.mesh.refreshBoundingInfo();
  53066. }
  53067. return this;
  53068. };
  53069. /**
  53070. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53071. * @param size the size (float) of the visibility box
  53072. * note : this doesn't lock the SPS mesh bounding box.
  53073. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53074. */
  53075. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53076. var vis = size / 2;
  53077. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53078. };
  53079. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53080. /**
  53081. * Gets whether the SPS as always visible or not
  53082. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53083. */
  53084. get: function () {
  53085. return this._alwaysVisible;
  53086. },
  53087. /**
  53088. * Sets the SPS as always visible or not
  53089. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53090. */
  53091. set: function (val) {
  53092. this._alwaysVisible = val;
  53093. this.mesh.alwaysSelectAsActiveMesh = val;
  53094. },
  53095. enumerable: true,
  53096. configurable: true
  53097. });
  53098. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53099. /**
  53100. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53101. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53102. */
  53103. get: function () {
  53104. return this._isVisibilityBoxLocked;
  53105. },
  53106. /**
  53107. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53108. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53109. */
  53110. set: function (val) {
  53111. this._isVisibilityBoxLocked = val;
  53112. var boundingInfo = this.mesh.getBoundingInfo();
  53113. boundingInfo.isLocked = val;
  53114. },
  53115. enumerable: true,
  53116. configurable: true
  53117. });
  53118. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53119. /**
  53120. * Gets if `setParticles()` computes the particle rotations or not.
  53121. * Default value : true. The SPS is faster when it's set to false.
  53122. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53123. */
  53124. get: function () {
  53125. return this._computeParticleRotation;
  53126. },
  53127. /**
  53128. * Tells to `setParticles()` to compute the particle rotations or not.
  53129. * Default value : true. The SPS is faster when it's set to false.
  53130. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53131. */
  53132. set: function (val) {
  53133. this._computeParticleRotation = val;
  53134. },
  53135. enumerable: true,
  53136. configurable: true
  53137. });
  53138. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53139. /**
  53140. * Gets if `setParticles()` computes the particle colors or not.
  53141. * Default value : true. The SPS is faster when it's set to false.
  53142. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53143. */
  53144. get: function () {
  53145. return this._computeParticleColor;
  53146. },
  53147. /**
  53148. * Tells to `setParticles()` to compute the particle colors or not.
  53149. * Default value : true. The SPS is faster when it's set to false.
  53150. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53151. */
  53152. set: function (val) {
  53153. this._computeParticleColor = val;
  53154. },
  53155. enumerable: true,
  53156. configurable: true
  53157. });
  53158. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53159. /**
  53160. * Gets if `setParticles()` computes the particle textures or not.
  53161. * Default value : true. The SPS is faster when it's set to false.
  53162. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53163. */
  53164. get: function () {
  53165. return this._computeParticleTexture;
  53166. },
  53167. set: function (val) {
  53168. this._computeParticleTexture = val;
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53174. /**
  53175. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53176. * Default value : false. The SPS is faster when it's set to false.
  53177. * Note : the particle custom vertex positions aren't stored values.
  53178. */
  53179. get: function () {
  53180. return this._computeParticleVertex;
  53181. },
  53182. /**
  53183. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53184. * Default value : false. The SPS is faster when it's set to false.
  53185. * Note : the particle custom vertex positions aren't stored values.
  53186. */
  53187. set: function (val) {
  53188. this._computeParticleVertex = val;
  53189. },
  53190. enumerable: true,
  53191. configurable: true
  53192. });
  53193. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53194. /**
  53195. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53196. */
  53197. get: function () {
  53198. return this._computeBoundingBox;
  53199. },
  53200. /**
  53201. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53202. */
  53203. set: function (val) {
  53204. this._computeBoundingBox = val;
  53205. },
  53206. enumerable: true,
  53207. configurable: true
  53208. });
  53209. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53210. /**
  53211. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53212. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53213. * Default : `true`
  53214. */
  53215. get: function () {
  53216. return this._depthSortParticles;
  53217. },
  53218. /**
  53219. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53220. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53221. * Default : `true`
  53222. */
  53223. set: function (val) {
  53224. this._depthSortParticles = val;
  53225. },
  53226. enumerable: true,
  53227. configurable: true
  53228. });
  53229. // =======================================================================
  53230. // Particle behavior logic
  53231. // these following methods may be overwritten by the user to fit his needs
  53232. /**
  53233. * This function does nothing. It may be overwritten to set all the particle first values.
  53234. * The SPS doesn't call this function, you may have to call it by your own.
  53235. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53236. */
  53237. SolidParticleSystem.prototype.initParticles = function () {
  53238. };
  53239. /**
  53240. * This function does nothing. It may be overwritten to recycle a particle.
  53241. * The SPS doesn't call this function, you may have to call it by your own.
  53242. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53243. * @param particle The particle to recycle
  53244. * @returns the recycled particle
  53245. */
  53246. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53247. return particle;
  53248. };
  53249. /**
  53250. * Updates a particle : this function should be overwritten by the user.
  53251. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53252. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53253. * @example : just set a particle position or velocity and recycle conditions
  53254. * @param particle The particle to update
  53255. * @returns the updated particle
  53256. */
  53257. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53258. return particle;
  53259. };
  53260. /**
  53261. * Updates a vertex of a particle : it can be overwritten by the user.
  53262. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53263. * @param particle the current particle
  53264. * @param vertex the current index of the current particle
  53265. * @param pt the index of the current vertex in the particle shape
  53266. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53267. * @example : just set a vertex particle position
  53268. * @returns the updated vertex
  53269. */
  53270. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53271. return vertex;
  53272. };
  53273. /**
  53274. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53275. * This does nothing and may be overwritten by the user.
  53276. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53277. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53278. * @param update the boolean update value actually passed to setParticles()
  53279. */
  53280. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53281. };
  53282. /**
  53283. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53284. * This will be passed three parameters.
  53285. * This does nothing and may be overwritten by the user.
  53286. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53287. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53288. * @param update the boolean update value actually passed to setParticles()
  53289. */
  53290. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53291. };
  53292. return SolidParticleSystem;
  53293. }());
  53294. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53295. })(BABYLON || (BABYLON = {}));
  53296. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53297. var BABYLON;
  53298. (function (BABYLON) {
  53299. var ShaderMaterial = /** @class */ (function (_super) {
  53300. __extends(ShaderMaterial, _super);
  53301. function ShaderMaterial(name, scene, shaderPath, options) {
  53302. var _this = _super.call(this, name, scene) || this;
  53303. _this._textures = {};
  53304. _this._textureArrays = {};
  53305. _this._floats = {};
  53306. _this._ints = {};
  53307. _this._floatsArrays = {};
  53308. _this._colors3 = {};
  53309. _this._colors3Arrays = {};
  53310. _this._colors4 = {};
  53311. _this._vectors2 = {};
  53312. _this._vectors3 = {};
  53313. _this._vectors4 = {};
  53314. _this._matrices = {};
  53315. _this._matrices3x3 = {};
  53316. _this._matrices2x2 = {};
  53317. _this._vectors2Arrays = {};
  53318. _this._vectors3Arrays = {};
  53319. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53320. _this._shaderPath = shaderPath;
  53321. options.needAlphaBlending = options.needAlphaBlending || false;
  53322. options.needAlphaTesting = options.needAlphaTesting || false;
  53323. options.attributes = options.attributes || ["position", "normal", "uv"];
  53324. options.uniforms = options.uniforms || ["worldViewProjection"];
  53325. options.uniformBuffers = options.uniformBuffers || [];
  53326. options.samplers = options.samplers || [];
  53327. options.defines = options.defines || [];
  53328. _this._options = options;
  53329. return _this;
  53330. }
  53331. ShaderMaterial.prototype.getClassName = function () {
  53332. return "ShaderMaterial";
  53333. };
  53334. ShaderMaterial.prototype.needAlphaBlending = function () {
  53335. return this._options.needAlphaBlending;
  53336. };
  53337. ShaderMaterial.prototype.needAlphaTesting = function () {
  53338. return this._options.needAlphaTesting;
  53339. };
  53340. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53341. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53342. this._options.uniforms.push(uniformName);
  53343. }
  53344. };
  53345. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53346. if (this._options.samplers.indexOf(name) === -1) {
  53347. this._options.samplers.push(name);
  53348. }
  53349. this._textures[name] = texture;
  53350. return this;
  53351. };
  53352. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53353. if (this._options.samplers.indexOf(name) === -1) {
  53354. this._options.samplers.push(name);
  53355. }
  53356. this._checkUniform(name);
  53357. this._textureArrays[name] = textures;
  53358. return this;
  53359. };
  53360. ShaderMaterial.prototype.setFloat = function (name, value) {
  53361. this._checkUniform(name);
  53362. this._floats[name] = value;
  53363. return this;
  53364. };
  53365. ShaderMaterial.prototype.setInt = function (name, value) {
  53366. this._checkUniform(name);
  53367. this._ints[name] = value;
  53368. return this;
  53369. };
  53370. ShaderMaterial.prototype.setFloats = function (name, value) {
  53371. this._checkUniform(name);
  53372. this._floatsArrays[name] = value;
  53373. return this;
  53374. };
  53375. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53376. this._checkUniform(name);
  53377. this._colors3[name] = value;
  53378. return this;
  53379. };
  53380. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53381. this._checkUniform(name);
  53382. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53383. color.toArray(arr, arr.length);
  53384. return arr;
  53385. }, []);
  53386. return this;
  53387. };
  53388. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53389. this._checkUniform(name);
  53390. this._colors4[name] = value;
  53391. return this;
  53392. };
  53393. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53394. this._checkUniform(name);
  53395. this._vectors2[name] = value;
  53396. return this;
  53397. };
  53398. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53399. this._checkUniform(name);
  53400. this._vectors3[name] = value;
  53401. return this;
  53402. };
  53403. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53404. this._checkUniform(name);
  53405. this._vectors4[name] = value;
  53406. return this;
  53407. };
  53408. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53409. this._checkUniform(name);
  53410. this._matrices[name] = value;
  53411. return this;
  53412. };
  53413. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53414. this._checkUniform(name);
  53415. this._matrices3x3[name] = value;
  53416. return this;
  53417. };
  53418. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53419. this._checkUniform(name);
  53420. this._matrices2x2[name] = value;
  53421. return this;
  53422. };
  53423. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53424. this._checkUniform(name);
  53425. this._vectors2Arrays[name] = value;
  53426. return this;
  53427. };
  53428. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53429. this._checkUniform(name);
  53430. this._vectors3Arrays[name] = value;
  53431. return this;
  53432. };
  53433. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53434. if (!mesh) {
  53435. return true;
  53436. }
  53437. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53438. return false;
  53439. }
  53440. return false;
  53441. };
  53442. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53443. var scene = this.getScene();
  53444. var engine = scene.getEngine();
  53445. if (!this.checkReadyOnEveryCall) {
  53446. if (this._renderId === scene.getRenderId()) {
  53447. if (this._checkCache(scene, mesh, useInstances)) {
  53448. return true;
  53449. }
  53450. }
  53451. }
  53452. // Instances
  53453. var defines = [];
  53454. var attribs = [];
  53455. var fallbacks = new BABYLON.EffectFallbacks();
  53456. if (useInstances) {
  53457. defines.push("#define INSTANCES");
  53458. }
  53459. for (var index = 0; index < this._options.defines.length; index++) {
  53460. defines.push(this._options.defines[index]);
  53461. }
  53462. for (var index = 0; index < this._options.attributes.length; index++) {
  53463. attribs.push(this._options.attributes[index]);
  53464. }
  53465. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53466. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53467. defines.push("#define VERTEXCOLOR");
  53468. }
  53469. // Bones
  53470. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53473. if (mesh.numBoneInfluencers > 4) {
  53474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53476. }
  53477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53478. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53479. fallbacks.addCPUSkinningFallback(0, mesh);
  53480. if (this._options.uniforms.indexOf("mBones") === -1) {
  53481. this._options.uniforms.push("mBones");
  53482. }
  53483. }
  53484. else {
  53485. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53486. }
  53487. // Textures
  53488. for (var name in this._textures) {
  53489. if (!this._textures[name].isReady()) {
  53490. return false;
  53491. }
  53492. }
  53493. // Alpha test
  53494. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53495. defines.push("#define ALPHATEST");
  53496. }
  53497. var previousEffect = this._effect;
  53498. var join = defines.join("\n");
  53499. this._effect = engine.createEffect(this._shaderPath, {
  53500. attributes: attribs,
  53501. uniformsNames: this._options.uniforms,
  53502. uniformBuffersNames: this._options.uniformBuffers,
  53503. samplers: this._options.samplers,
  53504. defines: join,
  53505. fallbacks: fallbacks,
  53506. onCompiled: this.onCompiled,
  53507. onError: this.onError
  53508. }, engine);
  53509. if (!this._effect.isReady()) {
  53510. return false;
  53511. }
  53512. if (previousEffect !== this._effect) {
  53513. scene.resetCachedMaterial();
  53514. }
  53515. this._renderId = scene.getRenderId();
  53516. return true;
  53517. };
  53518. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53519. var scene = this.getScene();
  53520. if (!this._effect) {
  53521. return;
  53522. }
  53523. if (this._options.uniforms.indexOf("world") !== -1) {
  53524. this._effect.setMatrix("world", world);
  53525. }
  53526. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53527. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53528. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53529. }
  53530. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53531. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53532. }
  53533. };
  53534. ShaderMaterial.prototype.bind = function (world, mesh) {
  53535. // Std values
  53536. this.bindOnlyWorldMatrix(world);
  53537. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53538. if (this._options.uniforms.indexOf("view") !== -1) {
  53539. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53540. }
  53541. if (this._options.uniforms.indexOf("projection") !== -1) {
  53542. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53543. }
  53544. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53545. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53546. }
  53547. // Bones
  53548. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53549. var name;
  53550. // Texture
  53551. for (name in this._textures) {
  53552. this._effect.setTexture(name, this._textures[name]);
  53553. }
  53554. // Texture arrays
  53555. for (name in this._textureArrays) {
  53556. this._effect.setTextureArray(name, this._textureArrays[name]);
  53557. }
  53558. // Int
  53559. for (name in this._ints) {
  53560. this._effect.setInt(name, this._ints[name]);
  53561. }
  53562. // Float
  53563. for (name in this._floats) {
  53564. this._effect.setFloat(name, this._floats[name]);
  53565. }
  53566. // Floats
  53567. for (name in this._floatsArrays) {
  53568. this._effect.setArray(name, this._floatsArrays[name]);
  53569. }
  53570. // Color3
  53571. for (name in this._colors3) {
  53572. this._effect.setColor3(name, this._colors3[name]);
  53573. }
  53574. for (name in this._colors3Arrays) {
  53575. this._effect.setArray3(name, this._colors3Arrays[name]);
  53576. }
  53577. // Color4
  53578. for (name in this._colors4) {
  53579. var color = this._colors4[name];
  53580. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53581. }
  53582. // Vector2
  53583. for (name in this._vectors2) {
  53584. this._effect.setVector2(name, this._vectors2[name]);
  53585. }
  53586. // Vector3
  53587. for (name in this._vectors3) {
  53588. this._effect.setVector3(name, this._vectors3[name]);
  53589. }
  53590. // Vector4
  53591. for (name in this._vectors4) {
  53592. this._effect.setVector4(name, this._vectors4[name]);
  53593. }
  53594. // Matrix
  53595. for (name in this._matrices) {
  53596. this._effect.setMatrix(name, this._matrices[name]);
  53597. }
  53598. // Matrix 3x3
  53599. for (name in this._matrices3x3) {
  53600. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53601. }
  53602. // Matrix 2x2
  53603. for (name in this._matrices2x2) {
  53604. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53605. }
  53606. // Vector2Array
  53607. for (name in this._vectors2Arrays) {
  53608. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53609. }
  53610. // Vector3Array
  53611. for (name in this._vectors3Arrays) {
  53612. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53613. }
  53614. }
  53615. this._afterBind(mesh);
  53616. };
  53617. ShaderMaterial.prototype.getActiveTextures = function () {
  53618. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53619. for (var name in this._textures) {
  53620. activeTextures.push(this._textures[name]);
  53621. }
  53622. for (var name in this._textureArrays) {
  53623. var array = this._textureArrays[name];
  53624. for (var index = 0; index < array.length; index++) {
  53625. activeTextures.push(array[index]);
  53626. }
  53627. }
  53628. return activeTextures;
  53629. };
  53630. ShaderMaterial.prototype.hasTexture = function (texture) {
  53631. if (_super.prototype.hasTexture.call(this, texture)) {
  53632. return true;
  53633. }
  53634. for (var name in this._textures) {
  53635. if (this._textures[name] === texture) {
  53636. return true;
  53637. }
  53638. }
  53639. for (var name in this._textureArrays) {
  53640. var array = this._textureArrays[name];
  53641. for (var index = 0; index < array.length; index++) {
  53642. if (array[index] === texture) {
  53643. return true;
  53644. }
  53645. }
  53646. }
  53647. return false;
  53648. };
  53649. ShaderMaterial.prototype.clone = function (name) {
  53650. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53651. return newShaderMaterial;
  53652. };
  53653. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53654. if (forceDisposeTextures) {
  53655. var name;
  53656. for (name in this._textures) {
  53657. this._textures[name].dispose();
  53658. }
  53659. for (name in this._textureArrays) {
  53660. var array = this._textureArrays[name];
  53661. for (var index = 0; index < array.length; index++) {
  53662. array[index].dispose();
  53663. }
  53664. }
  53665. }
  53666. this._textures = {};
  53667. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53668. };
  53669. ShaderMaterial.prototype.serialize = function () {
  53670. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53671. serializationObject.customType = "BABYLON.ShaderMaterial";
  53672. serializationObject.options = this._options;
  53673. serializationObject.shaderPath = this._shaderPath;
  53674. var name;
  53675. // Texture
  53676. serializationObject.textures = {};
  53677. for (name in this._textures) {
  53678. serializationObject.textures[name] = this._textures[name].serialize();
  53679. }
  53680. // Texture arrays
  53681. serializationObject.textureArrays = {};
  53682. for (name in this._textureArrays) {
  53683. serializationObject.textureArrays[name] = [];
  53684. var array = this._textureArrays[name];
  53685. for (var index = 0; index < array.length; index++) {
  53686. serializationObject.textureArrays[name].push(array[index].serialize());
  53687. }
  53688. }
  53689. // Float
  53690. serializationObject.floats = {};
  53691. for (name in this._floats) {
  53692. serializationObject.floats[name] = this._floats[name];
  53693. }
  53694. // Float s
  53695. serializationObject.FloatArrays = {};
  53696. for (name in this._floatsArrays) {
  53697. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53698. }
  53699. // Color3
  53700. serializationObject.colors3 = {};
  53701. for (name in this._colors3) {
  53702. serializationObject.colors3[name] = this._colors3[name].asArray();
  53703. }
  53704. // Color3 array
  53705. serializationObject.colors3Arrays = {};
  53706. for (name in this._colors3Arrays) {
  53707. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53708. }
  53709. // Color4
  53710. serializationObject.colors4 = {};
  53711. for (name in this._colors4) {
  53712. serializationObject.colors4[name] = this._colors4[name].asArray();
  53713. }
  53714. // Vector2
  53715. serializationObject.vectors2 = {};
  53716. for (name in this._vectors2) {
  53717. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53718. }
  53719. // Vector3
  53720. serializationObject.vectors3 = {};
  53721. for (name in this._vectors3) {
  53722. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53723. }
  53724. // Vector4
  53725. serializationObject.vectors4 = {};
  53726. for (name in this._vectors4) {
  53727. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53728. }
  53729. // Matrix
  53730. serializationObject.matrices = {};
  53731. for (name in this._matrices) {
  53732. serializationObject.matrices[name] = this._matrices[name].asArray();
  53733. }
  53734. // Matrix 3x3
  53735. serializationObject.matrices3x3 = {};
  53736. for (name in this._matrices3x3) {
  53737. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53738. }
  53739. // Matrix 2x2
  53740. serializationObject.matrices2x2 = {};
  53741. for (name in this._matrices2x2) {
  53742. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53743. }
  53744. // Vector2Array
  53745. serializationObject.vectors2Arrays = {};
  53746. for (name in this._vectors2Arrays) {
  53747. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53748. }
  53749. // Vector3Array
  53750. serializationObject.vectors3Arrays = {};
  53751. for (name in this._vectors3Arrays) {
  53752. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53753. }
  53754. return serializationObject;
  53755. };
  53756. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53757. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53758. var name;
  53759. // Texture
  53760. for (name in source.textures) {
  53761. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53762. }
  53763. // Texture arrays
  53764. for (name in source.textureArrays) {
  53765. var array = source.textureArrays[name];
  53766. var textureArray = new Array();
  53767. for (var index = 0; index < array.length; index++) {
  53768. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53769. }
  53770. material.setTextureArray(name, textureArray);
  53771. }
  53772. // Float
  53773. for (name in source.floats) {
  53774. material.setFloat(name, source.floats[name]);
  53775. }
  53776. // Float s
  53777. for (name in source.floatsArrays) {
  53778. material.setFloats(name, source.floatsArrays[name]);
  53779. }
  53780. // Color3
  53781. for (name in source.colors3) {
  53782. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53783. }
  53784. // Color3 arrays
  53785. for (name in source.colors3Arrays) {
  53786. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53787. if (i % 3 === 0) {
  53788. arr.push([num]);
  53789. }
  53790. else {
  53791. arr[arr.length - 1].push(num);
  53792. }
  53793. return arr;
  53794. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53795. material.setColor3Array(name, colors);
  53796. }
  53797. // Color4
  53798. for (name in source.colors4) {
  53799. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53800. }
  53801. // Vector2
  53802. for (name in source.vectors2) {
  53803. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53804. }
  53805. // Vector3
  53806. for (name in source.vectors3) {
  53807. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53808. }
  53809. // Vector4
  53810. for (name in source.vectors4) {
  53811. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53812. }
  53813. // Matrix
  53814. for (name in source.matrices) {
  53815. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53816. }
  53817. // Matrix 3x3
  53818. for (name in source.matrices3x3) {
  53819. material.setMatrix3x3(name, source.matrices3x3[name]);
  53820. }
  53821. // Matrix 2x2
  53822. for (name in source.matrices2x2) {
  53823. material.setMatrix2x2(name, source.matrices2x2[name]);
  53824. }
  53825. // Vector2Array
  53826. for (name in source.vectors2Arrays) {
  53827. material.setArray2(name, source.vectors2Arrays[name]);
  53828. }
  53829. // Vector3Array
  53830. for (name in source.vectors3Arrays) {
  53831. material.setArray3(name, source.vectors3Arrays[name]);
  53832. }
  53833. return material;
  53834. };
  53835. return ShaderMaterial;
  53836. }(BABYLON.Material));
  53837. BABYLON.ShaderMaterial = ShaderMaterial;
  53838. })(BABYLON || (BABYLON = {}));
  53839. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53840. var BABYLON;
  53841. (function (BABYLON) {
  53842. var GroundMesh = /** @class */ (function (_super) {
  53843. __extends(GroundMesh, _super);
  53844. function GroundMesh(name, scene) {
  53845. var _this = _super.call(this, name, scene) || this;
  53846. _this.generateOctree = false;
  53847. return _this;
  53848. }
  53849. GroundMesh.prototype.getClassName = function () {
  53850. return "GroundMesh";
  53851. };
  53852. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53853. get: function () {
  53854. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53855. },
  53856. enumerable: true,
  53857. configurable: true
  53858. });
  53859. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53860. get: function () {
  53861. return this._subdivisionsX;
  53862. },
  53863. enumerable: true,
  53864. configurable: true
  53865. });
  53866. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53867. get: function () {
  53868. return this._subdivisionsY;
  53869. },
  53870. enumerable: true,
  53871. configurable: true
  53872. });
  53873. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53874. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53875. this._subdivisionsX = chunksCount;
  53876. this._subdivisionsY = chunksCount;
  53877. this.subdivide(chunksCount);
  53878. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53879. };
  53880. /**
  53881. * Returns a height (y) value in the Worl system :
  53882. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53883. * Returns the ground y position if (x, z) are outside the ground surface.
  53884. */
  53885. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53886. var world = this.getWorldMatrix();
  53887. var invMat = BABYLON.Tmp.Matrix[5];
  53888. world.invertToRef(invMat);
  53889. var tmpVect = BABYLON.Tmp.Vector3[8];
  53890. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53891. x = tmpVect.x;
  53892. z = tmpVect.z;
  53893. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53894. return this.position.y;
  53895. }
  53896. if (!this._heightQuads || this._heightQuads.length == 0) {
  53897. this._initHeightQuads();
  53898. this._computeHeightQuads();
  53899. }
  53900. var facet = this._getFacetAt(x, z);
  53901. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53902. // return y in the World system
  53903. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53904. return tmpVect.y;
  53905. };
  53906. /**
  53907. * Returns a normalized vector (Vector3) orthogonal to the ground
  53908. * at the ground coordinates (x, z) expressed in the World system.
  53909. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53910. */
  53911. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53912. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53913. this.getNormalAtCoordinatesToRef(x, z, normal);
  53914. return normal;
  53915. };
  53916. /**
  53917. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53918. * at the ground coordinates (x, z) expressed in the World system.
  53919. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53920. * Returns the GroundMesh.
  53921. */
  53922. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53923. var world = this.getWorldMatrix();
  53924. var tmpMat = BABYLON.Tmp.Matrix[5];
  53925. world.invertToRef(tmpMat);
  53926. var tmpVect = BABYLON.Tmp.Vector3[8];
  53927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53928. x = tmpVect.x;
  53929. z = tmpVect.z;
  53930. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53931. return this;
  53932. }
  53933. if (!this._heightQuads || this._heightQuads.length == 0) {
  53934. this._initHeightQuads();
  53935. this._computeHeightQuads();
  53936. }
  53937. var facet = this._getFacetAt(x, z);
  53938. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53939. return this;
  53940. };
  53941. /**
  53942. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53943. * if the ground has been updated.
  53944. * This can be used in the render loop.
  53945. * Returns the GroundMesh.
  53946. */
  53947. GroundMesh.prototype.updateCoordinateHeights = function () {
  53948. if (!this._heightQuads || this._heightQuads.length == 0) {
  53949. this._initHeightQuads();
  53950. }
  53951. this._computeHeightQuads();
  53952. return this;
  53953. };
  53954. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53955. GroundMesh.prototype._getFacetAt = function (x, z) {
  53956. // retrieve col and row from x, z coordinates in the ground local system
  53957. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53958. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53959. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53960. var facet;
  53961. if (z < quad.slope.x * x + quad.slope.y) {
  53962. facet = quad.facet1;
  53963. }
  53964. else {
  53965. facet = quad.facet2;
  53966. }
  53967. return facet;
  53968. };
  53969. // Creates and populates the heightMap array with "facet" elements :
  53970. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53971. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53972. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53973. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53974. // Returns the GroundMesh.
  53975. GroundMesh.prototype._initHeightQuads = function () {
  53976. var subdivisionsX = this._subdivisionsX;
  53977. var subdivisionsY = this._subdivisionsY;
  53978. this._heightQuads = new Array();
  53979. for (var row = 0; row < subdivisionsY; row++) {
  53980. for (var col = 0; col < subdivisionsX; col++) {
  53981. 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) };
  53982. this._heightQuads[row * subdivisionsX + col] = quad;
  53983. }
  53984. }
  53985. return this;
  53986. };
  53987. // Compute each quad element values and update the the heightMap array :
  53988. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53989. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53990. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53991. // Returns the GroundMesh.
  53992. GroundMesh.prototype._computeHeightQuads = function () {
  53993. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53994. if (!positions) {
  53995. return this;
  53996. }
  53997. var v1 = BABYLON.Tmp.Vector3[3];
  53998. var v2 = BABYLON.Tmp.Vector3[2];
  53999. var v3 = BABYLON.Tmp.Vector3[1];
  54000. var v4 = BABYLON.Tmp.Vector3[0];
  54001. var v1v2 = BABYLON.Tmp.Vector3[4];
  54002. var v1v3 = BABYLON.Tmp.Vector3[5];
  54003. var v1v4 = BABYLON.Tmp.Vector3[6];
  54004. var norm1 = BABYLON.Tmp.Vector3[7];
  54005. var norm2 = BABYLON.Tmp.Vector3[8];
  54006. var i = 0;
  54007. var j = 0;
  54008. var k = 0;
  54009. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54010. var h = 0;
  54011. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54012. var d2 = 0;
  54013. var subdivisionsX = this._subdivisionsX;
  54014. var subdivisionsY = this._subdivisionsY;
  54015. for (var row = 0; row < subdivisionsY; row++) {
  54016. for (var col = 0; col < subdivisionsX; col++) {
  54017. i = col * 3;
  54018. j = row * (subdivisionsX + 1) * 3;
  54019. k = (row + 1) * (subdivisionsX + 1) * 3;
  54020. v1.x = positions[j + i];
  54021. v1.y = positions[j + i + 1];
  54022. v1.z = positions[j + i + 2];
  54023. v2.x = positions[j + i + 3];
  54024. v2.y = positions[j + i + 4];
  54025. v2.z = positions[j + i + 5];
  54026. v3.x = positions[k + i];
  54027. v3.y = positions[k + i + 1];
  54028. v3.z = positions[k + i + 2];
  54029. v4.x = positions[k + i + 3];
  54030. v4.y = positions[k + i + 4];
  54031. v4.z = positions[k + i + 5];
  54032. // 2D slope V1V4
  54033. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54034. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54035. // facet equations :
  54036. // we compute each facet normal vector
  54037. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54038. // we compute the value d by applying the equation to v1 which belongs to the plane
  54039. // then we store the facet equation in a Vector4
  54040. v2.subtractToRef(v1, v1v2);
  54041. v3.subtractToRef(v1, v1v3);
  54042. v4.subtractToRef(v1, v1v4);
  54043. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54044. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54045. norm1.normalize();
  54046. norm2.normalize();
  54047. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54048. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54049. var quad = this._heightQuads[row * subdivisionsX + col];
  54050. quad.slope.copyFromFloats(cd, h);
  54051. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54052. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54053. }
  54054. }
  54055. return this;
  54056. };
  54057. GroundMesh.prototype.serialize = function (serializationObject) {
  54058. _super.prototype.serialize.call(this, serializationObject);
  54059. serializationObject.subdivisionsX = this._subdivisionsX;
  54060. serializationObject.subdivisionsY = this._subdivisionsY;
  54061. serializationObject.minX = this._minX;
  54062. serializationObject.maxX = this._maxX;
  54063. serializationObject.minZ = this._minZ;
  54064. serializationObject.maxZ = this._maxZ;
  54065. serializationObject.width = this._width;
  54066. serializationObject.height = this._height;
  54067. };
  54068. GroundMesh.Parse = function (parsedMesh, scene) {
  54069. var result = new GroundMesh(parsedMesh.name, scene);
  54070. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54071. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54072. result._minX = parsedMesh.minX;
  54073. result._maxX = parsedMesh.maxX;
  54074. result._minZ = parsedMesh.minZ;
  54075. result._maxZ = parsedMesh.maxZ;
  54076. result._width = parsedMesh.width;
  54077. result._height = parsedMesh.height;
  54078. return result;
  54079. };
  54080. return GroundMesh;
  54081. }(BABYLON.Mesh));
  54082. BABYLON.GroundMesh = GroundMesh;
  54083. })(BABYLON || (BABYLON = {}));
  54084. //# sourceMappingURL=babylon.groundMesh.js.map
  54085. var BABYLON;
  54086. (function (BABYLON) {
  54087. /**
  54088. * Creates an instance based on a source mesh.
  54089. */
  54090. var InstancedMesh = /** @class */ (function (_super) {
  54091. __extends(InstancedMesh, _super);
  54092. function InstancedMesh(name, source) {
  54093. var _this = _super.call(this, name, source.getScene()) || this;
  54094. source.instances.push(_this);
  54095. _this._sourceMesh = source;
  54096. _this.position.copyFrom(source.position);
  54097. _this.rotation.copyFrom(source.rotation);
  54098. _this.scaling.copyFrom(source.scaling);
  54099. if (source.rotationQuaternion) {
  54100. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54101. }
  54102. _this.infiniteDistance = source.infiniteDistance;
  54103. _this.setPivotMatrix(source.getPivotMatrix());
  54104. _this.refreshBoundingInfo();
  54105. _this._syncSubMeshes();
  54106. return _this;
  54107. }
  54108. /**
  54109. * Returns the string "InstancedMesh".
  54110. */
  54111. InstancedMesh.prototype.getClassName = function () {
  54112. return "InstancedMesh";
  54113. };
  54114. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54115. // Methods
  54116. get: function () {
  54117. return this._sourceMesh.receiveShadows;
  54118. },
  54119. enumerable: true,
  54120. configurable: true
  54121. });
  54122. Object.defineProperty(InstancedMesh.prototype, "material", {
  54123. get: function () {
  54124. return this._sourceMesh.material;
  54125. },
  54126. enumerable: true,
  54127. configurable: true
  54128. });
  54129. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54130. get: function () {
  54131. return this._sourceMesh.visibility;
  54132. },
  54133. enumerable: true,
  54134. configurable: true
  54135. });
  54136. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54137. get: function () {
  54138. return this._sourceMesh.skeleton;
  54139. },
  54140. enumerable: true,
  54141. configurable: true
  54142. });
  54143. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54144. get: function () {
  54145. return this._sourceMesh.renderingGroupId;
  54146. },
  54147. enumerable: true,
  54148. configurable: true
  54149. });
  54150. /**
  54151. * Returns the total number of vertices (integer).
  54152. */
  54153. InstancedMesh.prototype.getTotalVertices = function () {
  54154. return this._sourceMesh.getTotalVertices();
  54155. };
  54156. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54157. get: function () {
  54158. return this._sourceMesh;
  54159. },
  54160. enumerable: true,
  54161. configurable: true
  54162. });
  54163. /**
  54164. * Is this node ready to be used/rendered
  54165. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54166. * @return {boolean} is it ready
  54167. */
  54168. InstancedMesh.prototype.isReady = function (completeCheck) {
  54169. if (completeCheck === void 0) { completeCheck = false; }
  54170. return this._sourceMesh.isReady(completeCheck, true);
  54171. };
  54172. /**
  54173. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54174. */
  54175. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54176. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54177. };
  54178. /**
  54179. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54180. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54181. * The `data` are either a numeric array either a Float32Array.
  54182. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54183. * 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).
  54184. * Note that a new underlying VertexBuffer object is created each call.
  54185. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54186. *
  54187. * Possible `kind` values :
  54188. * - BABYLON.VertexBuffer.PositionKind
  54189. * - BABYLON.VertexBuffer.UVKind
  54190. * - BABYLON.VertexBuffer.UV2Kind
  54191. * - BABYLON.VertexBuffer.UV3Kind
  54192. * - BABYLON.VertexBuffer.UV4Kind
  54193. * - BABYLON.VertexBuffer.UV5Kind
  54194. * - BABYLON.VertexBuffer.UV6Kind
  54195. * - BABYLON.VertexBuffer.ColorKind
  54196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54200. *
  54201. * Returns the Mesh.
  54202. */
  54203. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54204. if (this.sourceMesh) {
  54205. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54206. }
  54207. return this.sourceMesh;
  54208. };
  54209. /**
  54210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54211. * If the mesh has no geometry, it is simply returned as it is.
  54212. * The `data` are either a numeric array either a Float32Array.
  54213. * No new underlying VertexBuffer object is created.
  54214. * 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.
  54215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54216. *
  54217. * Possible `kind` values :
  54218. * - BABYLON.VertexBuffer.PositionKind
  54219. * - BABYLON.VertexBuffer.UVKind
  54220. * - BABYLON.VertexBuffer.UV2Kind
  54221. * - BABYLON.VertexBuffer.UV3Kind
  54222. * - BABYLON.VertexBuffer.UV4Kind
  54223. * - BABYLON.VertexBuffer.UV5Kind
  54224. * - BABYLON.VertexBuffer.UV6Kind
  54225. * - BABYLON.VertexBuffer.ColorKind
  54226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54230. *
  54231. * Returns the Mesh.
  54232. */
  54233. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54234. if (this.sourceMesh) {
  54235. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54236. }
  54237. return this.sourceMesh;
  54238. };
  54239. /**
  54240. * Sets the mesh indices.
  54241. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54242. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54243. * This method creates a new index buffer each call.
  54244. * Returns the Mesh.
  54245. */
  54246. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54247. if (totalVertices === void 0) { totalVertices = null; }
  54248. if (this.sourceMesh) {
  54249. this.sourceMesh.setIndices(indices, totalVertices);
  54250. }
  54251. return this.sourceMesh;
  54252. };
  54253. /**
  54254. * Boolean : True if the mesh owns the requested kind of data.
  54255. */
  54256. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54257. return this._sourceMesh.isVerticesDataPresent(kind);
  54258. };
  54259. /**
  54260. * Returns an array of indices (IndicesArray).
  54261. */
  54262. InstancedMesh.prototype.getIndices = function () {
  54263. return this._sourceMesh.getIndices();
  54264. };
  54265. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54266. get: function () {
  54267. return this._sourceMesh._positions;
  54268. },
  54269. enumerable: true,
  54270. configurable: true
  54271. });
  54272. /**
  54273. * Sets a new updated BoundingInfo to the mesh.
  54274. * Returns the mesh.
  54275. */
  54276. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54277. var meshBB = this._sourceMesh.getBoundingInfo();
  54278. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54279. this._updateBoundingInfo();
  54280. return this;
  54281. };
  54282. InstancedMesh.prototype._preActivate = function () {
  54283. if (this._currentLOD) {
  54284. this._currentLOD._preActivate();
  54285. }
  54286. return this;
  54287. };
  54288. InstancedMesh.prototype._activate = function (renderId) {
  54289. if (this._currentLOD) {
  54290. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54291. }
  54292. return this;
  54293. };
  54294. /**
  54295. * Returns the current associated LOD AbstractMesh.
  54296. */
  54297. InstancedMesh.prototype.getLOD = function (camera) {
  54298. if (!camera) {
  54299. return this;
  54300. }
  54301. var boundingInfo = this.getBoundingInfo();
  54302. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54303. if (this._currentLOD === this.sourceMesh) {
  54304. return this;
  54305. }
  54306. return this._currentLOD;
  54307. };
  54308. InstancedMesh.prototype._syncSubMeshes = function () {
  54309. this.releaseSubMeshes();
  54310. if (this._sourceMesh.subMeshes) {
  54311. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54312. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54313. }
  54314. }
  54315. return this;
  54316. };
  54317. InstancedMesh.prototype._generatePointsArray = function () {
  54318. return this._sourceMesh._generatePointsArray();
  54319. };
  54320. /**
  54321. * Creates a new InstancedMesh from the current mesh.
  54322. * - name (string) : the cloned mesh name
  54323. * - newParent (optional Node) : the optional Node to parent the clone to.
  54324. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54325. *
  54326. * Returns the clone.
  54327. */
  54328. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54329. var result = this._sourceMesh.createInstance(name);
  54330. // Deep copy
  54331. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54332. // Bounding info
  54333. this.refreshBoundingInfo();
  54334. // Parent
  54335. if (newParent) {
  54336. result.parent = newParent;
  54337. }
  54338. if (!doNotCloneChildren) {
  54339. // Children
  54340. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54341. var mesh = this.getScene().meshes[index];
  54342. if (mesh.parent === this) {
  54343. mesh.clone(mesh.name, result);
  54344. }
  54345. }
  54346. }
  54347. result.computeWorldMatrix(true);
  54348. return result;
  54349. };
  54350. /**
  54351. * Disposes the InstancedMesh.
  54352. * Returns nothing.
  54353. */
  54354. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54355. // Remove from mesh
  54356. var index = this._sourceMesh.instances.indexOf(this);
  54357. this._sourceMesh.instances.splice(index, 1);
  54358. _super.prototype.dispose.call(this, doNotRecurse);
  54359. };
  54360. return InstancedMesh;
  54361. }(BABYLON.AbstractMesh));
  54362. BABYLON.InstancedMesh = InstancedMesh;
  54363. })(BABYLON || (BABYLON = {}));
  54364. //# sourceMappingURL=babylon.instancedMesh.js.map
  54365. var BABYLON;
  54366. (function (BABYLON) {
  54367. var LinesMesh = /** @class */ (function (_super) {
  54368. __extends(LinesMesh, _super);
  54369. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54370. if (scene === void 0) { scene = null; }
  54371. if (parent === void 0) { parent = null; }
  54372. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54373. _this.useVertexColor = useVertexColor;
  54374. _this.useVertexAlpha = useVertexAlpha;
  54375. _this.color = new BABYLON.Color3(1, 1, 1);
  54376. _this.alpha = 1;
  54377. if (source) {
  54378. _this.color = source.color.clone();
  54379. _this.alpha = source.alpha;
  54380. _this.useVertexColor = source.useVertexColor;
  54381. _this.useVertexAlpha = source.useVertexAlpha;
  54382. }
  54383. _this._intersectionThreshold = 0.1;
  54384. var defines = [];
  54385. var options = {
  54386. attributes: [BABYLON.VertexBuffer.PositionKind],
  54387. uniforms: ["world", "viewProjection"],
  54388. needAlphaBlending: true,
  54389. defines: defines
  54390. };
  54391. if (useVertexAlpha === false) {
  54392. options.needAlphaBlending = false;
  54393. }
  54394. if (!useVertexColor) {
  54395. options.uniforms.push("color");
  54396. }
  54397. else {
  54398. options.defines.push("#define VERTEXCOLOR");
  54399. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54400. }
  54401. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54402. return _this;
  54403. }
  54404. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54405. /**
  54406. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54407. * This margin is expressed in world space coordinates, so its value may vary.
  54408. * Default value is 0.1
  54409. * @returns the intersection Threshold value.
  54410. */
  54411. get: function () {
  54412. return this._intersectionThreshold;
  54413. },
  54414. /**
  54415. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54416. * This margin is expressed in world space coordinates, so its value may vary.
  54417. * @param value the new threshold to apply
  54418. */
  54419. set: function (value) {
  54420. if (this._intersectionThreshold === value) {
  54421. return;
  54422. }
  54423. this._intersectionThreshold = value;
  54424. if (this.geometry) {
  54425. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54426. }
  54427. },
  54428. enumerable: true,
  54429. configurable: true
  54430. });
  54431. /**
  54432. * Returns the string "LineMesh"
  54433. */
  54434. LinesMesh.prototype.getClassName = function () {
  54435. return "LinesMesh";
  54436. };
  54437. Object.defineProperty(LinesMesh.prototype, "material", {
  54438. get: function () {
  54439. return this._colorShader;
  54440. },
  54441. set: function (value) {
  54442. // Do nothing
  54443. },
  54444. enumerable: true,
  54445. configurable: true
  54446. });
  54447. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54448. get: function () {
  54449. return false;
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. LinesMesh.prototype.createInstance = function (name) {
  54455. throw new Error("LinesMeshes do not support createInstance.");
  54456. };
  54457. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54458. if (!this._geometry) {
  54459. return this;
  54460. }
  54461. // VBOs
  54462. this._geometry._bind(this._colorShader.getEffect());
  54463. // Color
  54464. if (!this.useVertexColor) {
  54465. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54466. }
  54467. return this;
  54468. };
  54469. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54470. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54471. return this;
  54472. }
  54473. var engine = this.getScene().getEngine();
  54474. // Draw order
  54475. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54476. return this;
  54477. };
  54478. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54479. this._colorShader.dispose();
  54480. _super.prototype.dispose.call(this, doNotRecurse);
  54481. };
  54482. /**
  54483. * Returns a new LineMesh object cloned from the current one.
  54484. */
  54485. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54486. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54487. };
  54488. return LinesMesh;
  54489. }(BABYLON.Mesh));
  54490. BABYLON.LinesMesh = LinesMesh;
  54491. })(BABYLON || (BABYLON = {}));
  54492. //# sourceMappingURL=babylon.linesMesh.js.map
  54493. var BABYLON;
  54494. (function (BABYLON) {
  54495. var MeshBuilder = /** @class */ (function () {
  54496. function MeshBuilder() {
  54497. }
  54498. MeshBuilder.updateSideOrientation = function (orientation) {
  54499. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54500. return BABYLON.Mesh.DOUBLESIDE;
  54501. }
  54502. if (orientation === undefined || orientation === null) {
  54503. return BABYLON.Mesh.FRONTSIDE;
  54504. }
  54505. return orientation;
  54506. };
  54507. /**
  54508. * Creates a box mesh.
  54509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54510. * The parameter `size` sets the size (float) of each box side (default 1).
  54511. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54512. * 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).
  54513. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54515. * 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).
  54516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54518. */
  54519. MeshBuilder.CreateBox = function (name, options, scene) {
  54520. if (scene === void 0) { scene = null; }
  54521. var box = new BABYLON.Mesh(name, scene);
  54522. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54523. box._originalBuilderSideOrientation = options.sideOrientation;
  54524. var vertexData = BABYLON.VertexData.CreateBox(options);
  54525. vertexData.applyToMesh(box, options.updatable);
  54526. return box;
  54527. };
  54528. /**
  54529. * Creates a sphere mesh.
  54530. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54531. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54532. * 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`).
  54533. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54534. * 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
  54535. * 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).
  54536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54537. * 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).
  54538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54540. */
  54541. MeshBuilder.CreateSphere = function (name, options, scene) {
  54542. var sphere = new BABYLON.Mesh(name, scene);
  54543. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54544. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54545. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54546. vertexData.applyToMesh(sphere, options.updatable);
  54547. return sphere;
  54548. };
  54549. /**
  54550. * Creates a plane polygonal mesh. By default, this is a disc.
  54551. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54552. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54553. * 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.
  54554. * 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
  54555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54556. * 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).
  54557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54559. */
  54560. MeshBuilder.CreateDisc = function (name, options, scene) {
  54561. if (scene === void 0) { scene = null; }
  54562. var disc = new BABYLON.Mesh(name, scene);
  54563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54564. disc._originalBuilderSideOrientation = options.sideOrientation;
  54565. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54566. vertexData.applyToMesh(disc, options.updatable);
  54567. return disc;
  54568. };
  54569. /**
  54570. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54572. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54573. * 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`).
  54574. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54575. * 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.
  54576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54577. * 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).
  54578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54580. */
  54581. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54582. var sphere = new BABYLON.Mesh(name, scene);
  54583. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54584. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54585. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54586. vertexData.applyToMesh(sphere, options.updatable);
  54587. return sphere;
  54588. };
  54589. ;
  54590. /**
  54591. * Creates a ribbon mesh.
  54592. * 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.
  54593. *
  54594. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54595. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54596. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54597. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54598. * 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.
  54599. * 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.
  54600. * 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
  54601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54602. * 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).
  54603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54604. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54605. * 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.
  54606. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54607. * 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
  54608. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54609. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54611. */
  54612. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54613. if (scene === void 0) { scene = null; }
  54614. var pathArray = options.pathArray;
  54615. var closeArray = options.closeArray;
  54616. var closePath = options.closePath;
  54617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54618. var instance = options.instance;
  54619. var updatable = options.updatable;
  54620. if (instance) {
  54621. // positionFunction : ribbon case
  54622. // only pathArray and sideOrientation parameters are taken into account for positions update
  54623. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54624. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54625. var positionFunction = function (positions) {
  54626. var minlg = pathArray[0].length;
  54627. var i = 0;
  54628. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54629. for (var si = 1; si <= ns; si++) {
  54630. for (var p = 0; p < pathArray.length; p++) {
  54631. var path = pathArray[p];
  54632. var l = path.length;
  54633. minlg = (minlg < l) ? minlg : l;
  54634. var j = 0;
  54635. while (j < minlg) {
  54636. positions[i] = path[j].x;
  54637. positions[i + 1] = path[j].y;
  54638. positions[i + 2] = path[j].z;
  54639. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54640. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54641. }
  54642. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54643. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54644. }
  54645. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54646. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54647. }
  54648. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54649. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54650. }
  54651. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54652. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54653. }
  54654. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54655. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54656. }
  54657. j++;
  54658. i += 3;
  54659. }
  54660. if (instance._closePath) {
  54661. positions[i] = path[0].x;
  54662. positions[i + 1] = path[0].y;
  54663. positions[i + 2] = path[0].z;
  54664. i += 3;
  54665. }
  54666. }
  54667. }
  54668. };
  54669. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54670. positionFunction(positions);
  54671. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54672. instance._boundingInfo.update(instance._worldMatrix);
  54673. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54674. if (options.colors) {
  54675. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54676. for (var c = 0; c < options.colors.length; c++) {
  54677. colors[c * 4] = options.colors[c].r;
  54678. colors[c * 4 + 1] = options.colors[c].g;
  54679. colors[c * 4 + 2] = options.colors[c].b;
  54680. colors[c * 4 + 3] = options.colors[c].a;
  54681. }
  54682. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54683. }
  54684. if (options.uvs) {
  54685. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54686. for (var i = 0; i < options.uvs.length; i++) {
  54687. uvs[i * 2] = options.uvs[i].x;
  54688. uvs[i * 2 + 1] = options.uvs[i].y;
  54689. }
  54690. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54691. }
  54692. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54693. var indices = instance.getIndices();
  54694. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54695. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54696. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54697. if (instance._closePath) {
  54698. var indexFirst = 0;
  54699. var indexLast = 0;
  54700. for (var p = 0; p < pathArray.length; p++) {
  54701. indexFirst = instance._idx[p] * 3;
  54702. if (p + 1 < pathArray.length) {
  54703. indexLast = (instance._idx[p + 1] - 1) * 3;
  54704. }
  54705. else {
  54706. indexLast = normals.length - 3;
  54707. }
  54708. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54709. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54710. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54711. normals[indexLast] = normals[indexFirst];
  54712. normals[indexLast + 1] = normals[indexFirst + 1];
  54713. normals[indexLast + 2] = normals[indexFirst + 2];
  54714. }
  54715. }
  54716. if (!(instance.areNormalsFrozen)) {
  54717. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54718. }
  54719. }
  54720. return instance;
  54721. }
  54722. else {
  54723. var ribbon = new BABYLON.Mesh(name, scene);
  54724. ribbon._originalBuilderSideOrientation = sideOrientation;
  54725. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54726. if (closePath) {
  54727. ribbon._idx = vertexData._idx;
  54728. }
  54729. ribbon._closePath = closePath;
  54730. ribbon._closeArray = closeArray;
  54731. vertexData.applyToMesh(ribbon, updatable);
  54732. return ribbon;
  54733. }
  54734. };
  54735. /**
  54736. * Creates a cylinder or a cone mesh.
  54737. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54738. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54739. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54740. * 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.
  54741. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54742. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54743. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54744. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54745. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54746. * 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).
  54747. * 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
  54748. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54749. * 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
  54750. * 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.
  54751. * If `enclose` is false, a ring surface is one element.
  54752. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54753. * 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
  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.CreateCylinder = function (name, options, scene) {
  54760. var cylinder = new BABYLON.Mesh(name, scene);
  54761. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54762. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54763. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54764. vertexData.applyToMesh(cylinder, options.updatable);
  54765. return cylinder;
  54766. };
  54767. /**
  54768. * Creates a torus mesh.
  54769. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54770. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54771. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54772. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54774. * 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).
  54775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54777. */
  54778. MeshBuilder.CreateTorus = function (name, options, scene) {
  54779. var torus = new BABYLON.Mesh(name, scene);
  54780. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54781. torus._originalBuilderSideOrientation = options.sideOrientation;
  54782. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54783. vertexData.applyToMesh(torus, options.updatable);
  54784. return torus;
  54785. };
  54786. /**
  54787. * Creates a torus knot mesh.
  54788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54789. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54790. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54791. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54792. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54794. * 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).
  54795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54797. */
  54798. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54799. var torusKnot = new BABYLON.Mesh(name, scene);
  54800. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54801. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54802. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54803. vertexData.applyToMesh(torusKnot, options.updatable);
  54804. return torusKnot;
  54805. };
  54806. /**
  54807. * Creates a line system mesh.
  54808. * A line system is a pool of many lines gathered in a single mesh.
  54809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54810. * 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.
  54811. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54812. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54813. * 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
  54814. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54815. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54816. * 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
  54817. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54819. */
  54820. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54821. var instance = options.instance;
  54822. var lines = options.lines;
  54823. var colors = options.colors;
  54824. if (instance) {
  54825. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54826. var vertexColor;
  54827. var lineColors;
  54828. if (colors) {
  54829. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54830. }
  54831. var i = 0;
  54832. var c = 0;
  54833. for (var l = 0; l < lines.length; l++) {
  54834. var points = lines[l];
  54835. for (var p = 0; p < points.length; p++) {
  54836. positions[i] = points[p].x;
  54837. positions[i + 1] = points[p].y;
  54838. positions[i + 2] = points[p].z;
  54839. if (colors && vertexColor) {
  54840. lineColors = colors[l];
  54841. vertexColor[c] = lineColors[p].r;
  54842. vertexColor[c + 1] = lineColors[p].g;
  54843. vertexColor[c + 2] = lineColors[p].b;
  54844. vertexColor[c + 3] = lineColors[p].a;
  54845. c += 4;
  54846. }
  54847. i += 3;
  54848. }
  54849. }
  54850. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54851. if (colors && vertexColor) {
  54852. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54853. }
  54854. return instance;
  54855. }
  54856. // line system creation
  54857. var useVertexColor = (colors) ? true : false;
  54858. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54859. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54860. vertexData.applyToMesh(lineSystem, options.updatable);
  54861. return lineSystem;
  54862. };
  54863. /**
  54864. * Creates a line mesh.
  54865. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54866. * 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.
  54867. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54868. * The parameter `points` is an array successive Vector3.
  54869. * 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
  54870. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54871. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54872. * When updating an instance, remember that only point positions can change, not the number of points.
  54873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54874. */
  54875. MeshBuilder.CreateLines = function (name, options, scene) {
  54876. if (scene === void 0) { scene = null; }
  54877. var colors = (options.colors) ? [options.colors] : null;
  54878. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54879. return lines;
  54880. };
  54881. /**
  54882. * Creates a dashed line mesh.
  54883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54884. * 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.
  54885. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54886. * The parameter `points` is an array successive Vector3.
  54887. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54888. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54889. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54890. * 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
  54891. * When updating an instance, remember that only point positions can change, not the number of points.
  54892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54893. */
  54894. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54895. if (scene === void 0) { scene = null; }
  54896. var points = options.points;
  54897. var instance = options.instance;
  54898. var gapSize = options.gapSize || 1;
  54899. var dashSize = options.dashSize || 3;
  54900. if (instance) {
  54901. var positionFunction = function (positions) {
  54902. var curvect = BABYLON.Vector3.Zero();
  54903. var nbSeg = positions.length / 6;
  54904. var lg = 0;
  54905. var nb = 0;
  54906. var shft = 0;
  54907. var dashshft = 0;
  54908. var curshft = 0;
  54909. var p = 0;
  54910. var i = 0;
  54911. var j = 0;
  54912. for (i = 0; i < points.length - 1; i++) {
  54913. points[i + 1].subtractToRef(points[i], curvect);
  54914. lg += curvect.length();
  54915. }
  54916. shft = lg / nbSeg;
  54917. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54918. for (i = 0; i < points.length - 1; i++) {
  54919. points[i + 1].subtractToRef(points[i], curvect);
  54920. nb = Math.floor(curvect.length() / shft);
  54921. curvect.normalize();
  54922. j = 0;
  54923. while (j < nb && p < positions.length) {
  54924. curshft = shft * j;
  54925. positions[p] = points[i].x + curshft * curvect.x;
  54926. positions[p + 1] = points[i].y + curshft * curvect.y;
  54927. positions[p + 2] = points[i].z + curshft * curvect.z;
  54928. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54929. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54930. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54931. p += 6;
  54932. j++;
  54933. }
  54934. }
  54935. while (p < positions.length) {
  54936. positions[p] = points[i].x;
  54937. positions[p + 1] = points[i].y;
  54938. positions[p + 2] = points[i].z;
  54939. p += 3;
  54940. }
  54941. };
  54942. instance.updateMeshPositions(positionFunction, false);
  54943. return instance;
  54944. }
  54945. // dashed lines creation
  54946. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54947. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54948. vertexData.applyToMesh(dashedLines, options.updatable);
  54949. dashedLines.dashSize = dashSize;
  54950. dashedLines.gapSize = gapSize;
  54951. return dashedLines;
  54952. };
  54953. /**
  54954. * Creates an extruded shape mesh.
  54955. * 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.
  54956. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54957. *
  54958. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54959. * 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
  54960. * extruded along the Z axis.
  54961. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54962. * 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.
  54963. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54964. * 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
  54965. * 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
  54966. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54968. * 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).
  54969. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54970. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54972. */
  54973. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54974. if (scene === void 0) { scene = null; }
  54975. var path = options.path;
  54976. var shape = options.shape;
  54977. var scale = options.scale || 1;
  54978. var rotation = options.rotation || 0;
  54979. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54980. var updatable = options.updatable;
  54981. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54982. var instance = options.instance || null;
  54983. var invertUV = options.invertUV || false;
  54984. 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);
  54985. };
  54986. /**
  54987. * Creates an custom extruded shape mesh.
  54988. * 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.
  54989. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54990. *
  54991. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54992. * 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
  54993. * extruded along the Z axis.
  54994. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54995. * 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
  54996. * and the distance of this point from the begining of the path :
  54997. * ```javascript
  54998. * var rotationFunction = function(i, distance) {
  54999. * // do things
  55000. * return rotationValue; }
  55001. * ```
  55002. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55003. * 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
  55004. * and the distance of this point from the begining of the path :
  55005. * ```javascript
  55006. * var scaleFunction = function(i, distance) {
  55007. * // do things
  55008. * return scaleValue;}
  55009. * ```
  55010. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55011. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55012. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55013. * 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
  55014. * 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
  55015. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55017. * 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).
  55018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55019. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55021. */
  55022. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55023. var path = options.path;
  55024. var shape = options.shape;
  55025. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55026. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55027. var ribbonCloseArray = options.ribbonCloseArray || false;
  55028. var ribbonClosePath = options.ribbonClosePath || false;
  55029. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55030. var updatable = options.updatable;
  55031. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55032. var instance = options.instance;
  55033. var invertUV = options.invertUV || false;
  55034. 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);
  55035. };
  55036. /**
  55037. * Creates lathe mesh.
  55038. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55040. *
  55041. * 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
  55042. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55043. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55044. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55045. * 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.
  55046. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55047. * 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
  55048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55049. * 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).
  55050. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55051. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55053. */
  55054. MeshBuilder.CreateLathe = function (name, options, scene) {
  55055. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55056. var closed = (options.closed === undefined) ? true : options.closed;
  55057. var shape = options.shape;
  55058. var radius = options.radius || 1;
  55059. var tessellation = options.tessellation || 64;
  55060. var updatable = options.updatable;
  55061. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55062. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55063. var pi2 = Math.PI * 2;
  55064. var paths = new Array();
  55065. var invertUV = options.invertUV || false;
  55066. var i = 0;
  55067. var p = 0;
  55068. var step = pi2 / tessellation * arc;
  55069. var rotated;
  55070. var path = new Array();
  55071. ;
  55072. for (i = 0; i <= tessellation; i++) {
  55073. var path = [];
  55074. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55075. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55076. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55077. }
  55078. for (p = 0; p < shape.length; p++) {
  55079. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55080. path.push(rotated);
  55081. }
  55082. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55083. 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));
  55084. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55085. }
  55086. paths.push(path);
  55087. }
  55088. // lathe ribbon
  55089. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55090. return lathe;
  55091. };
  55092. /**
  55093. * Creates a plane mesh.
  55094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55095. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55096. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55097. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55099. * 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).
  55100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55102. */
  55103. MeshBuilder.CreatePlane = function (name, options, scene) {
  55104. var plane = new BABYLON.Mesh(name, scene);
  55105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55106. plane._originalBuilderSideOrientation = options.sideOrientation;
  55107. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55108. vertexData.applyToMesh(plane, options.updatable);
  55109. if (options.sourcePlane) {
  55110. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55111. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55112. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55113. plane.rotate(vectorProduct, product);
  55114. }
  55115. return plane;
  55116. };
  55117. /**
  55118. * Creates a ground mesh.
  55119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55120. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55121. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55123. */
  55124. MeshBuilder.CreateGround = function (name, options, scene) {
  55125. var ground = new BABYLON.GroundMesh(name, scene);
  55126. ground._setReady(false);
  55127. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55128. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55129. ground._width = options.width || 1;
  55130. ground._height = options.height || 1;
  55131. ground._maxX = ground._width / 2;
  55132. ground._maxZ = ground._height / 2;
  55133. ground._minX = -ground._maxX;
  55134. ground._minZ = -ground._maxZ;
  55135. var vertexData = BABYLON.VertexData.CreateGround(options);
  55136. vertexData.applyToMesh(ground, options.updatable);
  55137. ground._setReady(true);
  55138. return ground;
  55139. };
  55140. /**
  55141. * Creates a tiled ground mesh.
  55142. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55143. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55144. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55145. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55146. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55147. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55148. * numbers of subdivisions on the ground width and height of each tile.
  55149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55150. */
  55151. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55152. var tiledGround = new BABYLON.Mesh(name, scene);
  55153. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55154. vertexData.applyToMesh(tiledGround, options.updatable);
  55155. return tiledGround;
  55156. };
  55157. /**
  55158. * Creates a ground mesh from a height map.
  55159. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55160. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55161. * The parameter `url` sets the URL of the height map image resource.
  55162. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55163. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55164. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55165. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55166. * 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.
  55167. * 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).
  55168. * This function is passed the newly built mesh :
  55169. * ```javascript
  55170. * function(mesh) { // do things
  55171. * return; }
  55172. * ```
  55173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55174. */
  55175. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55176. var width = options.width || 10.0;
  55177. var height = options.height || 10.0;
  55178. var subdivisions = options.subdivisions || 1 | 0;
  55179. var minHeight = options.minHeight || 0.0;
  55180. var maxHeight = options.maxHeight || 1.0;
  55181. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55182. var updatable = options.updatable;
  55183. var onReady = options.onReady;
  55184. var ground = new BABYLON.GroundMesh(name, scene);
  55185. ground._subdivisionsX = subdivisions;
  55186. ground._subdivisionsY = subdivisions;
  55187. ground._width = width;
  55188. ground._height = height;
  55189. ground._maxX = ground._width / 2.0;
  55190. ground._maxZ = ground._height / 2.0;
  55191. ground._minX = -ground._maxX;
  55192. ground._minZ = -ground._maxZ;
  55193. ground._setReady(false);
  55194. var onload = function (img) {
  55195. // Getting height map data
  55196. var canvas = document.createElement("canvas");
  55197. var context = canvas.getContext("2d");
  55198. if (!context) {
  55199. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55200. }
  55201. if (scene.isDisposed) {
  55202. return;
  55203. }
  55204. var bufferWidth = img.width;
  55205. var bufferHeight = img.height;
  55206. canvas.width = bufferWidth;
  55207. canvas.height = bufferHeight;
  55208. context.drawImage(img, 0, 0);
  55209. // Create VertexData from map data
  55210. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55211. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55212. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55213. width: width, height: height,
  55214. subdivisions: subdivisions,
  55215. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55216. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55217. });
  55218. vertexData.applyToMesh(ground, updatable);
  55219. ground._setReady(true);
  55220. //execute ready callback, if set
  55221. if (onReady) {
  55222. onReady(ground);
  55223. }
  55224. };
  55225. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55226. return ground;
  55227. };
  55228. /**
  55229. * Creates a polygon mesh.
  55230. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55231. * 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.
  55232. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55234. * 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).
  55235. * Remember you can only change the shape positions, not their number when updating a polygon.
  55236. */
  55237. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55238. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55239. var shape = options.shape;
  55240. var holes = options.holes || [];
  55241. var depth = options.depth || 0;
  55242. var contours = [];
  55243. var hole = [];
  55244. for (var i = 0; i < shape.length; i++) {
  55245. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55246. }
  55247. var epsilon = 0.00000001;
  55248. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55249. contours.pop();
  55250. }
  55251. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55252. for (var hNb = 0; hNb < holes.length; hNb++) {
  55253. hole = [];
  55254. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55255. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55256. }
  55257. polygonTriangulation.addHole(hole);
  55258. }
  55259. var polygon = polygonTriangulation.build(options.updatable, depth);
  55260. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55261. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55262. vertexData.applyToMesh(polygon, options.updatable);
  55263. return polygon;
  55264. };
  55265. ;
  55266. /**
  55267. * Creates an extruded polygon mesh, with depth in the Y direction.
  55268. * 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).
  55269. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55270. */
  55271. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55272. return MeshBuilder.CreatePolygon(name, options, scene);
  55273. };
  55274. ;
  55275. /**
  55276. * Creates a tube mesh.
  55277. * 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.
  55278. *
  55279. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55280. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55281. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55282. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55283. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55284. * 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.
  55285. * It must return a radius value (positive float) :
  55286. * ```javascript
  55287. * var radiusFunction = function(i, distance) {
  55288. * // do things
  55289. * return radius; }
  55290. * ```
  55291. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55292. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  55293. * 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
  55294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55295. * 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).
  55296. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55297. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55299. */
  55300. MeshBuilder.CreateTube = function (name, options, scene) {
  55301. var path = options.path;
  55302. var instance = options.instance;
  55303. var radius = 1.0;
  55304. if (instance) {
  55305. radius = instance.radius;
  55306. }
  55307. if (options.radius !== undefined) {
  55308. radius = options.radius;
  55309. }
  55310. ;
  55311. var tessellation = options.tessellation || 64 | 0;
  55312. var radiusFunction = options.radiusFunction || null;
  55313. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55314. var invertUV = options.invertUV || false;
  55315. var updatable = options.updatable;
  55316. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55317. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55318. // tube geometry
  55319. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55320. var tangents = path3D.getTangents();
  55321. var normals = path3D.getNormals();
  55322. var distances = path3D.getDistances();
  55323. var pi2 = Math.PI * 2;
  55324. var step = pi2 / tessellation * arc;
  55325. var returnRadius = function () { return radius; };
  55326. var radiusFunctionFinal = radiusFunction || returnRadius;
  55327. var circlePath;
  55328. var rad;
  55329. var normal;
  55330. var rotated;
  55331. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55332. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55333. for (var i = 0; i < path.length; i++) {
  55334. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55335. circlePath = Array(); // current circle array
  55336. normal = normals[i]; // current normal
  55337. for (var t = 0; t < tessellation; t++) {
  55338. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55339. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55340. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55341. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55342. circlePath[t] = rotated;
  55343. }
  55344. circlePaths[index] = circlePath;
  55345. index++;
  55346. }
  55347. // cap
  55348. var capPath = function (nbPoints, pathIndex) {
  55349. var pointCap = Array();
  55350. for (var i = 0; i < nbPoints; i++) {
  55351. pointCap.push(path[pathIndex]);
  55352. }
  55353. return pointCap;
  55354. };
  55355. switch (cap) {
  55356. case BABYLON.Mesh.NO_CAP:
  55357. break;
  55358. case BABYLON.Mesh.CAP_START:
  55359. circlePaths[0] = capPath(tessellation, 0);
  55360. circlePaths[1] = circlePaths[2].slice(0);
  55361. break;
  55362. case BABYLON.Mesh.CAP_END:
  55363. circlePaths[index] = circlePaths[index - 1].slice(0);
  55364. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55365. break;
  55366. case BABYLON.Mesh.CAP_ALL:
  55367. circlePaths[0] = capPath(tessellation, 0);
  55368. circlePaths[1] = circlePaths[2].slice(0);
  55369. circlePaths[index] = circlePaths[index - 1].slice(0);
  55370. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55371. break;
  55372. default:
  55373. break;
  55374. }
  55375. return circlePaths;
  55376. };
  55377. var path3D;
  55378. var pathArray;
  55379. if (instance) {
  55380. var arc = options.arc || instance.arc;
  55381. path3D = (instance.path3D).update(path);
  55382. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55383. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55384. instance.path3D = path3D;
  55385. instance.pathArray = pathArray;
  55386. instance.arc = arc;
  55387. instance.radius = radius;
  55388. return instance;
  55389. }
  55390. // tube creation
  55391. path3D = new BABYLON.Path3D(path);
  55392. var newPathArray = new Array();
  55393. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55394. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55395. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55396. tube.pathArray = pathArray;
  55397. tube.path3D = path3D;
  55398. tube.tessellation = tessellation;
  55399. tube.cap = cap;
  55400. tube.arc = options.arc;
  55401. tube.radius = radius;
  55402. return tube;
  55403. };
  55404. /**
  55405. * Creates a polyhedron mesh.
  55406. *
  55407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55408. * 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
  55409. * to choose the wanted type.
  55410. * The parameter `size` (positive float, default 1) sets the polygon size.
  55411. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55412. * 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`.
  55413. * 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
  55414. * 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)`).
  55415. * 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
  55416. * 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.
  55417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55418. * 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).
  55419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55421. */
  55422. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55423. var polyhedron = new BABYLON.Mesh(name, scene);
  55424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55425. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55426. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55427. vertexData.applyToMesh(polyhedron, options.updatable);
  55428. return polyhedron;
  55429. };
  55430. /**
  55431. * Creates a decal mesh.
  55432. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55433. * 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.
  55434. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55435. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55436. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55437. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55438. */
  55439. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55440. var indices = sourceMesh.getIndices();
  55441. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55442. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55443. var position = options.position || BABYLON.Vector3.Zero();
  55444. var normal = options.normal || BABYLON.Vector3.Up();
  55445. var size = options.size || BABYLON.Vector3.One();
  55446. var angle = options.angle || 0;
  55447. // Getting correct rotation
  55448. if (!normal) {
  55449. var target = new BABYLON.Vector3(0, 0, 1);
  55450. var camera = sourceMesh.getScene().activeCamera;
  55451. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55452. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55453. }
  55454. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55455. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55456. var pitch = Math.atan2(normal.y, len);
  55457. // Matrix
  55458. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55459. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55460. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55461. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55462. var vertexData = new BABYLON.VertexData();
  55463. vertexData.indices = [];
  55464. vertexData.positions = [];
  55465. vertexData.normals = [];
  55466. vertexData.uvs = [];
  55467. var currentVertexDataIndex = 0;
  55468. var extractDecalVector3 = function (indexId) {
  55469. var result = new BABYLON.PositionNormalVertex();
  55470. if (!indices || !positions || !normals) {
  55471. return result;
  55472. }
  55473. var vertexId = indices[indexId];
  55474. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55475. // Send vector to decal local world
  55476. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55477. // Get normal
  55478. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55479. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55480. return result;
  55481. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55482. var clip = function (vertices, axis) {
  55483. if (vertices.length === 0) {
  55484. return vertices;
  55485. }
  55486. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55487. var clipVertices = function (v0, v1) {
  55488. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55489. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55490. };
  55491. var result = new Array();
  55492. for (var index = 0; index < vertices.length; index += 3) {
  55493. var v1Out;
  55494. var v2Out;
  55495. var v3Out;
  55496. var total = 0;
  55497. var nV1 = null;
  55498. var nV2 = null;
  55499. var nV3 = null;
  55500. var nV4 = null;
  55501. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55502. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55503. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55504. v1Out = d1 > 0;
  55505. v2Out = d2 > 0;
  55506. v3Out = d3 > 0;
  55507. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55508. switch (total) {
  55509. case 0:
  55510. result.push(vertices[index]);
  55511. result.push(vertices[index + 1]);
  55512. result.push(vertices[index + 2]);
  55513. break;
  55514. case 1:
  55515. if (v1Out) {
  55516. nV1 = vertices[index + 1];
  55517. nV2 = vertices[index + 2];
  55518. nV3 = clipVertices(vertices[index], nV1);
  55519. nV4 = clipVertices(vertices[index], nV2);
  55520. }
  55521. if (v2Out) {
  55522. nV1 = vertices[index];
  55523. nV2 = vertices[index + 2];
  55524. nV3 = clipVertices(vertices[index + 1], nV1);
  55525. nV4 = clipVertices(vertices[index + 1], nV2);
  55526. result.push(nV3);
  55527. result.push(nV2.clone());
  55528. result.push(nV1.clone());
  55529. result.push(nV2.clone());
  55530. result.push(nV3.clone());
  55531. result.push(nV4);
  55532. break;
  55533. }
  55534. if (v3Out) {
  55535. nV1 = vertices[index];
  55536. nV2 = vertices[index + 1];
  55537. nV3 = clipVertices(vertices[index + 2], nV1);
  55538. nV4 = clipVertices(vertices[index + 2], nV2);
  55539. }
  55540. if (nV1 && nV2 && nV3 && nV4) {
  55541. result.push(nV1.clone());
  55542. result.push(nV2.clone());
  55543. result.push(nV3);
  55544. result.push(nV4);
  55545. result.push(nV3.clone());
  55546. result.push(nV2.clone());
  55547. }
  55548. break;
  55549. case 2:
  55550. if (!v1Out) {
  55551. nV1 = vertices[index].clone();
  55552. nV2 = clipVertices(nV1, vertices[index + 1]);
  55553. nV3 = clipVertices(nV1, vertices[index + 2]);
  55554. result.push(nV1);
  55555. result.push(nV2);
  55556. result.push(nV3);
  55557. }
  55558. if (!v2Out) {
  55559. nV1 = vertices[index + 1].clone();
  55560. nV2 = clipVertices(nV1, vertices[index + 2]);
  55561. nV3 = clipVertices(nV1, vertices[index]);
  55562. result.push(nV1);
  55563. result.push(nV2);
  55564. result.push(nV3);
  55565. }
  55566. if (!v3Out) {
  55567. nV1 = vertices[index + 2].clone();
  55568. nV2 = clipVertices(nV1, vertices[index]);
  55569. nV3 = clipVertices(nV1, vertices[index + 1]);
  55570. result.push(nV1);
  55571. result.push(nV2);
  55572. result.push(nV3);
  55573. }
  55574. break;
  55575. case 3:
  55576. break;
  55577. }
  55578. }
  55579. return result;
  55580. };
  55581. for (var index = 0; index < indices.length; index += 3) {
  55582. var faceVertices = new Array();
  55583. faceVertices.push(extractDecalVector3(index));
  55584. faceVertices.push(extractDecalVector3(index + 1));
  55585. faceVertices.push(extractDecalVector3(index + 2));
  55586. // Clip
  55587. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55588. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55589. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55590. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55591. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55592. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55593. if (faceVertices.length === 0) {
  55594. continue;
  55595. }
  55596. // Add UVs and get back to world
  55597. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55598. var vertex = faceVertices[vIndex];
  55599. //TODO check for Int32Array | Uint32Array | Uint16Array
  55600. vertexData.indices.push(currentVertexDataIndex);
  55601. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55602. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55603. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55604. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55605. currentVertexDataIndex++;
  55606. }
  55607. }
  55608. // Return mesh
  55609. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55610. vertexData.applyToMesh(decal);
  55611. decal.position = position.clone();
  55612. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55613. return decal;
  55614. };
  55615. // Privates
  55616. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55617. // extrusion geometry
  55618. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55619. var tangents = path3D.getTangents();
  55620. var normals = path3D.getNormals();
  55621. var binormals = path3D.getBinormals();
  55622. var distances = path3D.getDistances();
  55623. var angle = 0;
  55624. var returnScale = function () { return scale !== null ? scale : 1; };
  55625. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55626. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55627. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55628. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55629. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55630. for (var i = 0; i < curve.length; i++) {
  55631. var shapePath = new Array();
  55632. var angleStep = rotate(i, distances[i]);
  55633. var scaleRatio = scl(i, distances[i]);
  55634. for (var p = 0; p < shape.length; p++) {
  55635. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55636. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55637. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55638. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55639. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55640. shapePath[p] = rotated;
  55641. }
  55642. shapePaths[index] = shapePath;
  55643. angle += angleStep;
  55644. index++;
  55645. }
  55646. // cap
  55647. var capPath = function (shapePath) {
  55648. var pointCap = Array();
  55649. var barycenter = BABYLON.Vector3.Zero();
  55650. var i;
  55651. for (i = 0; i < shapePath.length; i++) {
  55652. barycenter.addInPlace(shapePath[i]);
  55653. }
  55654. barycenter.scaleInPlace(1.0 / shapePath.length);
  55655. for (i = 0; i < shapePath.length; i++) {
  55656. pointCap.push(barycenter);
  55657. }
  55658. return pointCap;
  55659. };
  55660. switch (cap) {
  55661. case BABYLON.Mesh.NO_CAP:
  55662. break;
  55663. case BABYLON.Mesh.CAP_START:
  55664. shapePaths[0] = capPath(shapePaths[2]);
  55665. shapePaths[1] = shapePaths[2];
  55666. break;
  55667. case BABYLON.Mesh.CAP_END:
  55668. shapePaths[index] = shapePaths[index - 1];
  55669. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55670. break;
  55671. case BABYLON.Mesh.CAP_ALL:
  55672. shapePaths[0] = capPath(shapePaths[2]);
  55673. shapePaths[1] = shapePaths[2];
  55674. shapePaths[index] = shapePaths[index - 1];
  55675. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55676. break;
  55677. default:
  55678. break;
  55679. }
  55680. return shapePaths;
  55681. };
  55682. var path3D;
  55683. var pathArray;
  55684. if (instance) {
  55685. path3D = (instance.path3D).update(curve);
  55686. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55687. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55688. return instance;
  55689. }
  55690. // extruded shape creation
  55691. path3D = new BABYLON.Path3D(curve);
  55692. var newShapePaths = new Array();
  55693. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55694. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55695. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55696. extrudedGeneric.pathArray = pathArray;
  55697. extrudedGeneric.path3D = path3D;
  55698. extrudedGeneric.cap = cap;
  55699. return extrudedGeneric;
  55700. };
  55701. return MeshBuilder;
  55702. }());
  55703. BABYLON.MeshBuilder = MeshBuilder;
  55704. })(BABYLON || (BABYLON = {}));
  55705. //# sourceMappingURL=babylon.meshBuilder.js.map
  55706. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  55707. var BABYLON;
  55708. (function (BABYLON) {
  55709. /**
  55710. * Draco compression (https://google.github.io/draco/)
  55711. */
  55712. var DracoCompression = /** @class */ (function () {
  55713. /**
  55714. * Constructor
  55715. * @param numWorkers The number of workers for async operations
  55716. */
  55717. function DracoCompression(numWorkers) {
  55718. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55719. var workers = new Array(numWorkers);
  55720. for (var i = 0; i < workers.length; i++) {
  55721. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  55722. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55723. workers[i] = worker;
  55724. }
  55725. this._workerPool = new BABYLON.WorkerPool(workers);
  55726. }
  55727. /**
  55728. * Stop all async operations and release resources.
  55729. */
  55730. DracoCompression.prototype.dispose = function () {
  55731. this._workerPool.dispose();
  55732. delete this._workerPool;
  55733. };
  55734. /**
  55735. * Decode Draco compressed mesh data to vertex data.
  55736. * @param data The array buffer view for the Draco compression data
  55737. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55738. * @returns A promise that resolves with the decoded vertex data
  55739. */
  55740. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55741. var _this = this;
  55742. return new Promise(function (resolve, reject) {
  55743. _this._workerPool.push(function (worker, onComplete) {
  55744. var vertexData = new BABYLON.VertexData();
  55745. var onError = function (error) {
  55746. worker.removeEventListener("error", onError);
  55747. worker.removeEventListener("message", onMessage);
  55748. reject(error);
  55749. onComplete();
  55750. };
  55751. var onMessage = function (message) {
  55752. if (message.data === "done") {
  55753. worker.removeEventListener("error", onError);
  55754. worker.removeEventListener("message", onMessage);
  55755. resolve(vertexData);
  55756. onComplete();
  55757. }
  55758. else if (message.data.id === "indices") {
  55759. vertexData.indices = message.data.value;
  55760. }
  55761. else {
  55762. vertexData.set(message.data.value, message.data.id);
  55763. }
  55764. };
  55765. worker.addEventListener("error", onError);
  55766. worker.addEventListener("message", onMessage);
  55767. var dataCopy = new Uint8Array(data.byteLength);
  55768. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55769. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55770. });
  55771. });
  55772. };
  55773. /**
  55774. * The worker function that gets converted to a blob url to pass into a worker.
  55775. */
  55776. DracoCompression._Worker = function () {
  55777. // self is actually a DedicatedWorkerGlobalScope
  55778. var _self = self;
  55779. var decodeMesh = function (data, attributes) {
  55780. var dracoModule = new DracoDecoderModule();
  55781. var buffer = new dracoModule.DecoderBuffer();
  55782. buffer.Init(data, data.byteLength);
  55783. var decoder = new dracoModule.Decoder();
  55784. var geometry;
  55785. var status;
  55786. try {
  55787. var type = decoder.GetEncodedGeometryType(buffer);
  55788. switch (type) {
  55789. case dracoModule.TRIANGULAR_MESH:
  55790. geometry = new dracoModule.Mesh();
  55791. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55792. break;
  55793. case dracoModule.POINT_CLOUD:
  55794. geometry = new dracoModule.PointCloud();
  55795. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55796. break;
  55797. default:
  55798. throw new Error("Invalid geometry type " + type);
  55799. }
  55800. if (!status.ok() || !geometry.ptr) {
  55801. throw new Error(status.error_msg());
  55802. }
  55803. var numPoints = geometry.num_points();
  55804. if (type === dracoModule.TRIANGULAR_MESH) {
  55805. var numFaces = geometry.num_faces();
  55806. var faceIndices = new dracoModule.DracoInt32Array();
  55807. try {
  55808. var indices = new Uint32Array(numFaces * 3);
  55809. for (var i = 0; i < numFaces; i++) {
  55810. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55811. var offset = i * 3;
  55812. indices[offset + 0] = faceIndices.GetValue(0);
  55813. indices[offset + 1] = faceIndices.GetValue(1);
  55814. indices[offset + 2] = faceIndices.GetValue(2);
  55815. }
  55816. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55817. }
  55818. finally {
  55819. dracoModule.destroy(faceIndices);
  55820. }
  55821. }
  55822. for (var kind in attributes) {
  55823. var uniqueId = attributes[kind];
  55824. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55825. var dracoData = new dracoModule.DracoFloat32Array();
  55826. try {
  55827. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55828. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55829. for (var i = 0; i < babylonData.length; i++) {
  55830. babylonData[i] = dracoData.GetValue(i);
  55831. }
  55832. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55833. }
  55834. finally {
  55835. dracoModule.destroy(dracoData);
  55836. }
  55837. }
  55838. }
  55839. finally {
  55840. if (geometry) {
  55841. dracoModule.destroy(geometry);
  55842. }
  55843. dracoModule.destroy(decoder);
  55844. dracoModule.destroy(buffer);
  55845. }
  55846. _self.postMessage("done");
  55847. };
  55848. _self.onmessage = function (event) {
  55849. switch (event.data.id) {
  55850. case "initDecoder": {
  55851. importScripts(event.data.url);
  55852. break;
  55853. }
  55854. case "decodeMesh": {
  55855. decodeMesh(event.data.data, event.data.attributes);
  55856. break;
  55857. }
  55858. }
  55859. };
  55860. };
  55861. DracoCompression._GetDefaultDecoderUrl = function () {
  55862. for (var i = 0; i < document.scripts.length; i++) {
  55863. if (document.scripts[i].type === "text/x-draco-decoder") {
  55864. return document.scripts[i].src;
  55865. }
  55866. }
  55867. return null;
  55868. };
  55869. /**
  55870. * Gets the url to the draco decoder if available.
  55871. */
  55872. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  55873. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55874. return DracoCompression;
  55875. }());
  55876. BABYLON.DracoCompression = DracoCompression;
  55877. })(BABYLON || (BABYLON = {}));
  55878. //# sourceMappingURL=babylon.dracoCompression.js.map
  55879. var BABYLON;
  55880. (function (BABYLON) {
  55881. var AudioEngine = /** @class */ (function () {
  55882. function AudioEngine() {
  55883. this._audioContext = null;
  55884. this._audioContextInitialized = false;
  55885. this.canUseWebAudio = false;
  55886. this.WarnedWebAudioUnsupported = false;
  55887. this.unlocked = false;
  55888. this.isMP3supported = false;
  55889. this.isOGGsupported = false;
  55890. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55891. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55892. this.canUseWebAudio = true;
  55893. }
  55894. var audioElem = document.createElement('audio');
  55895. try {
  55896. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55897. this.isMP3supported = true;
  55898. }
  55899. }
  55900. catch (e) {
  55901. // protect error during capability check.
  55902. }
  55903. try {
  55904. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55905. this.isOGGsupported = true;
  55906. }
  55907. }
  55908. catch (e) {
  55909. // protect error during capability check.
  55910. }
  55911. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55912. this._unlockiOSaudio();
  55913. }
  55914. else {
  55915. this.unlocked = true;
  55916. }
  55917. }
  55918. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55919. get: function () {
  55920. if (!this._audioContextInitialized) {
  55921. this._initializeAudioContext();
  55922. }
  55923. return this._audioContext;
  55924. },
  55925. enumerable: true,
  55926. configurable: true
  55927. });
  55928. AudioEngine.prototype._unlockiOSaudio = function () {
  55929. var _this = this;
  55930. var unlockaudio = function () {
  55931. if (!_this.audioContext) {
  55932. return;
  55933. }
  55934. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55935. var source = _this.audioContext.createBufferSource();
  55936. source.buffer = buffer;
  55937. source.connect(_this.audioContext.destination);
  55938. source.start(0);
  55939. setTimeout(function () {
  55940. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55941. _this.unlocked = true;
  55942. window.removeEventListener('touchend', unlockaudio, false);
  55943. if (_this.onAudioUnlocked) {
  55944. _this.onAudioUnlocked();
  55945. }
  55946. }
  55947. }, 0);
  55948. };
  55949. window.addEventListener('touchend', unlockaudio, false);
  55950. };
  55951. AudioEngine.prototype._initializeAudioContext = function () {
  55952. try {
  55953. if (this.canUseWebAudio) {
  55954. this._audioContext = new AudioContext();
  55955. // create a global volume gain node
  55956. this.masterGain = this._audioContext.createGain();
  55957. this.masterGain.gain.value = 1;
  55958. this.masterGain.connect(this._audioContext.destination);
  55959. this._audioContextInitialized = true;
  55960. }
  55961. }
  55962. catch (e) {
  55963. this.canUseWebAudio = false;
  55964. BABYLON.Tools.Error("Web Audio: " + e.message);
  55965. }
  55966. };
  55967. AudioEngine.prototype.dispose = function () {
  55968. if (this.canUseWebAudio && this._audioContextInitialized) {
  55969. if (this._connectedAnalyser && this._audioContext) {
  55970. this._connectedAnalyser.stopDebugCanvas();
  55971. this._connectedAnalyser.dispose();
  55972. this.masterGain.disconnect();
  55973. this.masterGain.connect(this._audioContext.destination);
  55974. this._connectedAnalyser = null;
  55975. }
  55976. this.masterGain.gain.value = 1;
  55977. }
  55978. this.WarnedWebAudioUnsupported = false;
  55979. };
  55980. AudioEngine.prototype.getGlobalVolume = function () {
  55981. if (this.canUseWebAudio && this._audioContextInitialized) {
  55982. return this.masterGain.gain.value;
  55983. }
  55984. else {
  55985. return -1;
  55986. }
  55987. };
  55988. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55989. if (this.canUseWebAudio && this._audioContextInitialized) {
  55990. this.masterGain.gain.value = newVolume;
  55991. }
  55992. };
  55993. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55994. if (this._connectedAnalyser) {
  55995. this._connectedAnalyser.stopDebugCanvas();
  55996. }
  55997. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55998. this._connectedAnalyser = analyser;
  55999. this.masterGain.disconnect();
  56000. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56001. }
  56002. };
  56003. return AudioEngine;
  56004. }());
  56005. BABYLON.AudioEngine = AudioEngine;
  56006. })(BABYLON || (BABYLON = {}));
  56007. //# sourceMappingURL=babylon.audioEngine.js.map
  56008. var BABYLON;
  56009. (function (BABYLON) {
  56010. var Sound = /** @class */ (function () {
  56011. /**
  56012. * Create a sound and attach it to a scene
  56013. * @param name Name of your sound
  56014. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56015. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56016. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56017. */
  56018. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56019. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56020. var _this = this;
  56021. this.autoplay = false;
  56022. this.loop = false;
  56023. this.useCustomAttenuation = false;
  56024. this.spatialSound = false;
  56025. this.refDistance = 1;
  56026. this.rolloffFactor = 1;
  56027. this.maxDistance = 100;
  56028. this.distanceModel = "linear";
  56029. this._panningModel = "equalpower";
  56030. this._playbackRate = 1;
  56031. this._streaming = false;
  56032. this._startTime = 0;
  56033. this._startOffset = 0;
  56034. this._position = BABYLON.Vector3.Zero();
  56035. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56036. this._volume = 1;
  56037. this._isReadyToPlay = false;
  56038. this.isPlaying = false;
  56039. this.isPaused = false;
  56040. this._isDirectional = false;
  56041. // Used if you'd like to create a directional sound.
  56042. // If not set, the sound will be omnidirectional
  56043. this._coneInnerAngle = 360;
  56044. this._coneOuterAngle = 360;
  56045. this._coneOuterGain = 0;
  56046. this._isOutputConnected = false;
  56047. this._urlType = "Unknown";
  56048. this.name = name;
  56049. this._scene = scene;
  56050. this._readyToPlayCallback = readyToPlayCallback;
  56051. // Default custom attenuation function is a linear attenuation
  56052. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56053. if (currentDistance < maxDistance) {
  56054. return currentVolume * (1 - currentDistance / maxDistance);
  56055. }
  56056. else {
  56057. return 0;
  56058. }
  56059. };
  56060. if (options) {
  56061. this.autoplay = options.autoplay || false;
  56062. this.loop = options.loop || false;
  56063. // if volume === 0, we need another way to check this option
  56064. if (options.volume !== undefined) {
  56065. this._volume = options.volume;
  56066. }
  56067. this.spatialSound = options.spatialSound || false;
  56068. this.maxDistance = options.maxDistance || 100;
  56069. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56070. this.rolloffFactor = options.rolloffFactor || 1;
  56071. this.refDistance = options.refDistance || 1;
  56072. this.distanceModel = options.distanceModel || "linear";
  56073. this._playbackRate = options.playbackRate || 1;
  56074. this._streaming = options.streaming || false;
  56075. }
  56076. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56077. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56078. this._soundGain.gain.value = this._volume;
  56079. this._inputAudioNode = this._soundGain;
  56080. this._ouputAudioNode = this._soundGain;
  56081. if (this.spatialSound) {
  56082. this._createSpatialParameters();
  56083. }
  56084. this._scene.mainSoundTrack.AddSound(this);
  56085. var validParameter = true;
  56086. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56087. if (urlOrArrayBuffer) {
  56088. if (typeof (urlOrArrayBuffer) === "string")
  56089. this._urlType = "String";
  56090. if (Array.isArray(urlOrArrayBuffer))
  56091. this._urlType = "Array";
  56092. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56093. this._urlType = "ArrayBuffer";
  56094. var urls = [];
  56095. var codecSupportedFound = false;
  56096. switch (this._urlType) {
  56097. case "ArrayBuffer":
  56098. if (urlOrArrayBuffer.byteLength > 0) {
  56099. codecSupportedFound = true;
  56100. this._soundLoaded(urlOrArrayBuffer);
  56101. }
  56102. break;
  56103. case "String":
  56104. urls.push(urlOrArrayBuffer);
  56105. case "Array":
  56106. if (urls.length === 0)
  56107. urls = urlOrArrayBuffer;
  56108. // If we found a supported format, we load it immediately and stop the loop
  56109. for (var i = 0; i < urls.length; i++) {
  56110. var url = urls[i];
  56111. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56112. codecSupportedFound = true;
  56113. }
  56114. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56115. codecSupportedFound = true;
  56116. }
  56117. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56118. codecSupportedFound = true;
  56119. }
  56120. if (url.indexOf("blob:") !== -1) {
  56121. codecSupportedFound = true;
  56122. }
  56123. if (codecSupportedFound) {
  56124. // Loading sound using XHR2
  56125. if (!this._streaming) {
  56126. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56127. }
  56128. else {
  56129. this._htmlAudioElement = new Audio(url);
  56130. this._htmlAudioElement.controls = false;
  56131. this._htmlAudioElement.loop = this.loop;
  56132. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56133. this._htmlAudioElement.preload = "auto";
  56134. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56135. _this._isReadyToPlay = true;
  56136. if (_this.autoplay) {
  56137. _this.play();
  56138. }
  56139. if (_this._readyToPlayCallback) {
  56140. _this._readyToPlayCallback();
  56141. }
  56142. });
  56143. document.body.appendChild(this._htmlAudioElement);
  56144. }
  56145. break;
  56146. }
  56147. }
  56148. break;
  56149. default:
  56150. validParameter = false;
  56151. break;
  56152. }
  56153. if (!validParameter) {
  56154. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56155. }
  56156. else {
  56157. if (!codecSupportedFound) {
  56158. this._isReadyToPlay = true;
  56159. // Simulating a ready to play event to avoid breaking code path
  56160. if (this._readyToPlayCallback) {
  56161. window.setTimeout(function () {
  56162. if (_this._readyToPlayCallback) {
  56163. _this._readyToPlayCallback();
  56164. }
  56165. }, 1000);
  56166. }
  56167. }
  56168. }
  56169. }
  56170. }
  56171. else {
  56172. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56173. this._scene.mainSoundTrack.AddSound(this);
  56174. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56175. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56176. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56177. }
  56178. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56179. if (this._readyToPlayCallback) {
  56180. window.setTimeout(function () {
  56181. if (_this._readyToPlayCallback) {
  56182. _this._readyToPlayCallback();
  56183. }
  56184. }, 1000);
  56185. }
  56186. }
  56187. }
  56188. Sound.prototype.dispose = function () {
  56189. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56190. if (this.isPlaying) {
  56191. this.stop();
  56192. }
  56193. this._isReadyToPlay = false;
  56194. if (this.soundTrackId === -1) {
  56195. this._scene.mainSoundTrack.RemoveSound(this);
  56196. }
  56197. else {
  56198. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56199. }
  56200. if (this._soundGain) {
  56201. this._soundGain.disconnect();
  56202. this._soundGain = null;
  56203. }
  56204. if (this._soundPanner) {
  56205. this._soundPanner.disconnect();
  56206. this._soundPanner = null;
  56207. }
  56208. if (this._soundSource) {
  56209. this._soundSource.disconnect();
  56210. this._soundSource = null;
  56211. }
  56212. this._audioBuffer = null;
  56213. if (this._htmlAudioElement) {
  56214. this._htmlAudioElement.pause();
  56215. this._htmlAudioElement.src = "";
  56216. document.body.removeChild(this._htmlAudioElement);
  56217. }
  56218. if (this._connectedMesh && this._registerFunc) {
  56219. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56220. this._connectedMesh = null;
  56221. }
  56222. }
  56223. };
  56224. Sound.prototype.isReady = function () {
  56225. return this._isReadyToPlay;
  56226. };
  56227. Sound.prototype._soundLoaded = function (audioData) {
  56228. var _this = this;
  56229. if (!BABYLON.Engine.audioEngine.audioContext) {
  56230. return;
  56231. }
  56232. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56233. _this._audioBuffer = buffer;
  56234. _this._isReadyToPlay = true;
  56235. if (_this.autoplay) {
  56236. _this.play();
  56237. }
  56238. if (_this._readyToPlayCallback) {
  56239. _this._readyToPlayCallback();
  56240. }
  56241. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56242. };
  56243. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56244. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56245. this._audioBuffer = audioBuffer;
  56246. this._isReadyToPlay = true;
  56247. }
  56248. };
  56249. Sound.prototype.updateOptions = function (options) {
  56250. if (options) {
  56251. this.loop = options.loop || this.loop;
  56252. this.maxDistance = options.maxDistance || this.maxDistance;
  56253. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56254. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56255. this.refDistance = options.refDistance || this.refDistance;
  56256. this.distanceModel = options.distanceModel || this.distanceModel;
  56257. this._playbackRate = options.playbackRate || this._playbackRate;
  56258. this._updateSpatialParameters();
  56259. if (this.isPlaying) {
  56260. if (this._streaming) {
  56261. this._htmlAudioElement.playbackRate = this._playbackRate;
  56262. }
  56263. else {
  56264. if (this._soundSource) {
  56265. this._soundSource.playbackRate.value = this._playbackRate;
  56266. }
  56267. }
  56268. }
  56269. }
  56270. };
  56271. Sound.prototype._createSpatialParameters = function () {
  56272. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56273. if (this._scene.headphone) {
  56274. this._panningModel = "HRTF";
  56275. }
  56276. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56277. this._updateSpatialParameters();
  56278. this._soundPanner.connect(this._ouputAudioNode);
  56279. this._inputAudioNode = this._soundPanner;
  56280. }
  56281. };
  56282. Sound.prototype._updateSpatialParameters = function () {
  56283. if (this.spatialSound && this._soundPanner) {
  56284. if (this.useCustomAttenuation) {
  56285. // Tricks to disable in a way embedded Web Audio attenuation
  56286. this._soundPanner.distanceModel = "linear";
  56287. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56288. this._soundPanner.refDistance = 1;
  56289. this._soundPanner.rolloffFactor = 1;
  56290. this._soundPanner.panningModel = this._panningModel;
  56291. }
  56292. else {
  56293. this._soundPanner.distanceModel = this.distanceModel;
  56294. this._soundPanner.maxDistance = this.maxDistance;
  56295. this._soundPanner.refDistance = this.refDistance;
  56296. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56297. this._soundPanner.panningModel = this._panningModel;
  56298. }
  56299. }
  56300. };
  56301. Sound.prototype.switchPanningModelToHRTF = function () {
  56302. this._panningModel = "HRTF";
  56303. this._switchPanningModel();
  56304. };
  56305. Sound.prototype.switchPanningModelToEqualPower = function () {
  56306. this._panningModel = "equalpower";
  56307. this._switchPanningModel();
  56308. };
  56309. Sound.prototype._switchPanningModel = function () {
  56310. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56311. this._soundPanner.panningModel = this._panningModel;
  56312. }
  56313. };
  56314. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56315. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56316. if (this._isOutputConnected) {
  56317. this._ouputAudioNode.disconnect();
  56318. }
  56319. this._ouputAudioNode.connect(soundTrackAudioNode);
  56320. this._isOutputConnected = true;
  56321. }
  56322. };
  56323. /**
  56324. * Transform this sound into a directional source
  56325. * @param coneInnerAngle Size of the inner cone in degree
  56326. * @param coneOuterAngle Size of the outer cone in degree
  56327. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56328. */
  56329. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56330. if (coneOuterAngle < coneInnerAngle) {
  56331. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56332. return;
  56333. }
  56334. this._coneInnerAngle = coneInnerAngle;
  56335. this._coneOuterAngle = coneOuterAngle;
  56336. this._coneOuterGain = coneOuterGain;
  56337. this._isDirectional = true;
  56338. if (this.isPlaying && this.loop) {
  56339. this.stop();
  56340. this.play();
  56341. }
  56342. };
  56343. Sound.prototype.setPosition = function (newPosition) {
  56344. this._position = newPosition;
  56345. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56346. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56347. }
  56348. };
  56349. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56350. this._localDirection = newLocalDirection;
  56351. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56352. this._updateDirection();
  56353. }
  56354. };
  56355. Sound.prototype._updateDirection = function () {
  56356. if (!this._connectedMesh || !this._soundPanner) {
  56357. return;
  56358. }
  56359. var mat = this._connectedMesh.getWorldMatrix();
  56360. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56361. direction.normalize();
  56362. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56363. };
  56364. Sound.prototype.updateDistanceFromListener = function () {
  56365. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56366. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56367. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56368. }
  56369. };
  56370. Sound.prototype.setAttenuationFunction = function (callback) {
  56371. this._customAttenuationFunction = callback;
  56372. };
  56373. /**
  56374. * Play the sound
  56375. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56376. * @param offset (optional) Start the sound setting it at a specific time
  56377. */
  56378. Sound.prototype.play = function (time, offset) {
  56379. var _this = this;
  56380. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56381. try {
  56382. if (this._startOffset < 0) {
  56383. time = -this._startOffset;
  56384. this._startOffset = 0;
  56385. }
  56386. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56387. if (!this._soundSource || !this._streamingSource) {
  56388. if (this.spatialSound && this._soundPanner) {
  56389. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56390. if (this._isDirectional) {
  56391. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56392. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56393. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56394. if (this._connectedMesh) {
  56395. this._updateDirection();
  56396. }
  56397. else {
  56398. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56399. }
  56400. }
  56401. }
  56402. }
  56403. if (this._streaming) {
  56404. if (!this._streamingSource) {
  56405. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56406. this._htmlAudioElement.onended = function () { _this._onended(); };
  56407. this._htmlAudioElement.playbackRate = this._playbackRate;
  56408. }
  56409. this._streamingSource.disconnect();
  56410. this._streamingSource.connect(this._inputAudioNode);
  56411. this._htmlAudioElement.play();
  56412. }
  56413. else {
  56414. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56415. this._soundSource.buffer = this._audioBuffer;
  56416. this._soundSource.connect(this._inputAudioNode);
  56417. this._soundSource.loop = this.loop;
  56418. this._soundSource.playbackRate.value = this._playbackRate;
  56419. this._soundSource.onended = function () { _this._onended(); };
  56420. if (this._soundSource.buffer) {
  56421. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56422. }
  56423. }
  56424. this._startTime = startTime;
  56425. this.isPlaying = true;
  56426. this.isPaused = false;
  56427. }
  56428. catch (ex) {
  56429. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56430. }
  56431. }
  56432. };
  56433. Sound.prototype._onended = function () {
  56434. this.isPlaying = false;
  56435. if (this.onended) {
  56436. this.onended();
  56437. }
  56438. };
  56439. /**
  56440. * Stop the sound
  56441. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56442. */
  56443. Sound.prototype.stop = function (time) {
  56444. if (this.isPlaying) {
  56445. if (this._streaming) {
  56446. this._htmlAudioElement.pause();
  56447. // Test needed for Firefox or it will generate an Invalid State Error
  56448. if (this._htmlAudioElement.currentTime > 0) {
  56449. this._htmlAudioElement.currentTime = 0;
  56450. }
  56451. }
  56452. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56453. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56454. this._soundSource.stop(stopTime);
  56455. this._soundSource.onended = function () { };
  56456. if (!this.isPaused) {
  56457. this._startOffset = 0;
  56458. }
  56459. }
  56460. this.isPlaying = false;
  56461. }
  56462. };
  56463. Sound.prototype.pause = function () {
  56464. if (this.isPlaying) {
  56465. this.isPaused = true;
  56466. if (this._streaming) {
  56467. this._htmlAudioElement.pause();
  56468. }
  56469. else if (BABYLON.Engine.audioEngine.audioContext) {
  56470. this.stop(0);
  56471. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56472. }
  56473. }
  56474. };
  56475. Sound.prototype.setVolume = function (newVolume, time) {
  56476. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56477. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56478. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56479. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56480. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56481. }
  56482. else {
  56483. this._soundGain.gain.value = newVolume;
  56484. }
  56485. }
  56486. this._volume = newVolume;
  56487. };
  56488. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56489. this._playbackRate = newPlaybackRate;
  56490. if (this.isPlaying) {
  56491. if (this._streaming) {
  56492. this._htmlAudioElement.playbackRate = this._playbackRate;
  56493. }
  56494. else if (this._soundSource) {
  56495. this._soundSource.playbackRate.value = this._playbackRate;
  56496. }
  56497. }
  56498. };
  56499. Sound.prototype.getVolume = function () {
  56500. return this._volume;
  56501. };
  56502. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56503. var _this = this;
  56504. if (this._connectedMesh && this._registerFunc) {
  56505. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56506. this._registerFunc = null;
  56507. }
  56508. this._connectedMesh = meshToConnectTo;
  56509. if (!this.spatialSound) {
  56510. this.spatialSound = true;
  56511. this._createSpatialParameters();
  56512. if (this.isPlaying && this.loop) {
  56513. this.stop();
  56514. this.play();
  56515. }
  56516. }
  56517. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56518. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56519. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56520. };
  56521. Sound.prototype.detachFromMesh = function () {
  56522. if (this._connectedMesh && this._registerFunc) {
  56523. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56524. this._registerFunc = null;
  56525. this._connectedMesh = null;
  56526. }
  56527. };
  56528. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56529. if (!node.getBoundingInfo) {
  56530. return;
  56531. }
  56532. var mesh = node;
  56533. var boundingInfo = mesh.getBoundingInfo();
  56534. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56535. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56536. this._updateDirection();
  56537. }
  56538. };
  56539. Sound.prototype.clone = function () {
  56540. var _this = this;
  56541. if (!this._streaming) {
  56542. var setBufferAndRun = function () {
  56543. if (_this._isReadyToPlay) {
  56544. clonedSound._audioBuffer = _this.getAudioBuffer();
  56545. clonedSound._isReadyToPlay = true;
  56546. if (clonedSound.autoplay) {
  56547. clonedSound.play();
  56548. }
  56549. }
  56550. else {
  56551. window.setTimeout(setBufferAndRun, 300);
  56552. }
  56553. };
  56554. var currentOptions = {
  56555. autoplay: this.autoplay, loop: this.loop,
  56556. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56557. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56558. refDistance: this.refDistance, distanceModel: this.distanceModel
  56559. };
  56560. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56561. if (this.useCustomAttenuation) {
  56562. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56563. }
  56564. clonedSound.setPosition(this._position);
  56565. clonedSound.setPlaybackRate(this._playbackRate);
  56566. setBufferAndRun();
  56567. return clonedSound;
  56568. }
  56569. else {
  56570. return null;
  56571. }
  56572. };
  56573. Sound.prototype.getAudioBuffer = function () {
  56574. return this._audioBuffer;
  56575. };
  56576. Sound.prototype.serialize = function () {
  56577. var serializationObject = {
  56578. name: this.name,
  56579. url: this.name,
  56580. autoplay: this.autoplay,
  56581. loop: this.loop,
  56582. volume: this._volume,
  56583. spatialSound: this.spatialSound,
  56584. maxDistance: this.maxDistance,
  56585. rolloffFactor: this.rolloffFactor,
  56586. refDistance: this.refDistance,
  56587. distanceModel: this.distanceModel,
  56588. playbackRate: this._playbackRate,
  56589. panningModel: this._panningModel,
  56590. soundTrackId: this.soundTrackId
  56591. };
  56592. if (this.spatialSound) {
  56593. if (this._connectedMesh)
  56594. serializationObject.connectedMeshId = this._connectedMesh.id;
  56595. serializationObject.position = this._position.asArray();
  56596. serializationObject.refDistance = this.refDistance;
  56597. serializationObject.distanceModel = this.distanceModel;
  56598. serializationObject.isDirectional = this._isDirectional;
  56599. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56600. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56601. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56602. serializationObject.coneOuterGain = this._coneOuterGain;
  56603. }
  56604. return serializationObject;
  56605. };
  56606. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56607. var soundName = parsedSound.name;
  56608. var soundUrl;
  56609. if (parsedSound.url) {
  56610. soundUrl = rootUrl + parsedSound.url;
  56611. }
  56612. else {
  56613. soundUrl = rootUrl + soundName;
  56614. }
  56615. var options = {
  56616. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56617. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56618. rolloffFactor: parsedSound.rolloffFactor,
  56619. refDistance: parsedSound.refDistance,
  56620. distanceModel: parsedSound.distanceModel,
  56621. playbackRate: parsedSound.playbackRate
  56622. };
  56623. var newSound;
  56624. if (!sourceSound) {
  56625. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56626. scene._addPendingData(newSound);
  56627. }
  56628. else {
  56629. var setBufferAndRun = function () {
  56630. if (sourceSound._isReadyToPlay) {
  56631. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56632. newSound._isReadyToPlay = true;
  56633. if (newSound.autoplay) {
  56634. newSound.play();
  56635. }
  56636. }
  56637. else {
  56638. window.setTimeout(setBufferAndRun, 300);
  56639. }
  56640. };
  56641. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56642. setBufferAndRun();
  56643. }
  56644. if (parsedSound.position) {
  56645. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56646. newSound.setPosition(soundPosition);
  56647. }
  56648. if (parsedSound.isDirectional) {
  56649. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56650. if (parsedSound.localDirectionToMesh) {
  56651. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56652. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56653. }
  56654. }
  56655. if (parsedSound.connectedMeshId) {
  56656. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56657. if (connectedMesh) {
  56658. newSound.attachToMesh(connectedMesh);
  56659. }
  56660. }
  56661. return newSound;
  56662. };
  56663. return Sound;
  56664. }());
  56665. BABYLON.Sound = Sound;
  56666. })(BABYLON || (BABYLON = {}));
  56667. //# sourceMappingURL=babylon.sound.js.map
  56668. var BABYLON;
  56669. (function (BABYLON) {
  56670. var SoundTrack = /** @class */ (function () {
  56671. function SoundTrack(scene, options) {
  56672. this.id = -1;
  56673. this._isMainTrack = false;
  56674. this._isInitialized = false;
  56675. this._scene = scene;
  56676. this.soundCollection = new Array();
  56677. this._options = options;
  56678. if (!this._isMainTrack) {
  56679. this._scene.soundTracks.push(this);
  56680. this.id = this._scene.soundTracks.length - 1;
  56681. }
  56682. }
  56683. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56684. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56685. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56686. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56687. if (this._options) {
  56688. if (this._options.volume) {
  56689. this._outputAudioNode.gain.value = this._options.volume;
  56690. }
  56691. if (this._options.mainTrack) {
  56692. this._isMainTrack = this._options.mainTrack;
  56693. }
  56694. }
  56695. this._isInitialized = true;
  56696. }
  56697. };
  56698. SoundTrack.prototype.dispose = function () {
  56699. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56700. if (this._connectedAnalyser) {
  56701. this._connectedAnalyser.stopDebugCanvas();
  56702. }
  56703. while (this.soundCollection.length) {
  56704. this.soundCollection[0].dispose();
  56705. }
  56706. if (this._outputAudioNode) {
  56707. this._outputAudioNode.disconnect();
  56708. }
  56709. this._outputAudioNode = null;
  56710. }
  56711. };
  56712. SoundTrack.prototype.AddSound = function (sound) {
  56713. if (!this._isInitialized) {
  56714. this._initializeSoundTrackAudioGraph();
  56715. }
  56716. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56717. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56718. }
  56719. if (sound.soundTrackId) {
  56720. if (sound.soundTrackId === -1) {
  56721. this._scene.mainSoundTrack.RemoveSound(sound);
  56722. }
  56723. else {
  56724. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56725. }
  56726. }
  56727. this.soundCollection.push(sound);
  56728. sound.soundTrackId = this.id;
  56729. };
  56730. SoundTrack.prototype.RemoveSound = function (sound) {
  56731. var index = this.soundCollection.indexOf(sound);
  56732. if (index !== -1) {
  56733. this.soundCollection.splice(index, 1);
  56734. }
  56735. };
  56736. SoundTrack.prototype.setVolume = function (newVolume) {
  56737. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56738. this._outputAudioNode.gain.value = newVolume;
  56739. }
  56740. };
  56741. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56742. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56743. for (var i = 0; i < this.soundCollection.length; i++) {
  56744. this.soundCollection[i].switchPanningModelToHRTF();
  56745. }
  56746. }
  56747. };
  56748. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56749. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56750. for (var i = 0; i < this.soundCollection.length; i++) {
  56751. this.soundCollection[i].switchPanningModelToEqualPower();
  56752. }
  56753. }
  56754. };
  56755. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56756. if (this._connectedAnalyser) {
  56757. this._connectedAnalyser.stopDebugCanvas();
  56758. }
  56759. this._connectedAnalyser = analyser;
  56760. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56761. this._outputAudioNode.disconnect();
  56762. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56763. }
  56764. };
  56765. return SoundTrack;
  56766. }());
  56767. BABYLON.SoundTrack = SoundTrack;
  56768. })(BABYLON || (BABYLON = {}));
  56769. //# sourceMappingURL=babylon.soundtrack.js.map
  56770. var BABYLON;
  56771. (function (BABYLON) {
  56772. var Analyser = /** @class */ (function () {
  56773. function Analyser(scene) {
  56774. this.SMOOTHING = 0.75;
  56775. this.FFT_SIZE = 512;
  56776. this.BARGRAPHAMPLITUDE = 256;
  56777. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56778. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56779. this._scene = scene;
  56780. this._audioEngine = BABYLON.Engine.audioEngine;
  56781. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56782. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56783. this._webAudioAnalyser.minDecibels = -140;
  56784. this._webAudioAnalyser.maxDecibels = 0;
  56785. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56786. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56787. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56788. }
  56789. }
  56790. Analyser.prototype.getFrequencyBinCount = function () {
  56791. if (this._audioEngine.canUseWebAudio) {
  56792. return this._webAudioAnalyser.frequencyBinCount;
  56793. }
  56794. else {
  56795. return 0;
  56796. }
  56797. };
  56798. Analyser.prototype.getByteFrequencyData = function () {
  56799. if (this._audioEngine.canUseWebAudio) {
  56800. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56801. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56802. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56803. }
  56804. return this._byteFreqs;
  56805. };
  56806. Analyser.prototype.getByteTimeDomainData = function () {
  56807. if (this._audioEngine.canUseWebAudio) {
  56808. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56809. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56810. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56811. }
  56812. return this._byteTime;
  56813. };
  56814. Analyser.prototype.getFloatFrequencyData = function () {
  56815. if (this._audioEngine.canUseWebAudio) {
  56816. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56817. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56818. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56819. }
  56820. return this._floatFreqs;
  56821. };
  56822. Analyser.prototype.drawDebugCanvas = function () {
  56823. var _this = this;
  56824. if (this._audioEngine.canUseWebAudio) {
  56825. if (!this._debugCanvas) {
  56826. this._debugCanvas = document.createElement("canvas");
  56827. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56828. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56829. this._debugCanvas.style.position = "absolute";
  56830. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56831. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56832. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56833. document.body.appendChild(this._debugCanvas);
  56834. this._registerFunc = function () {
  56835. _this.drawDebugCanvas();
  56836. };
  56837. this._scene.registerBeforeRender(this._registerFunc);
  56838. }
  56839. if (this._registerFunc && this._debugCanvasContext) {
  56840. var workingArray = this.getByteFrequencyData();
  56841. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56842. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56843. // Draw the frequency domain chart.
  56844. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56845. var value = workingArray[i];
  56846. var percent = value / this.BARGRAPHAMPLITUDE;
  56847. var height = this.DEBUGCANVASSIZE.height * percent;
  56848. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56849. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56850. var hue = i / this.getFrequencyBinCount() * 360;
  56851. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56852. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56853. }
  56854. }
  56855. }
  56856. };
  56857. Analyser.prototype.stopDebugCanvas = function () {
  56858. if (this._debugCanvas) {
  56859. if (this._registerFunc) {
  56860. this._scene.unregisterBeforeRender(this._registerFunc);
  56861. this._registerFunc = null;
  56862. }
  56863. document.body.removeChild(this._debugCanvas);
  56864. this._debugCanvas = null;
  56865. this._debugCanvasContext = null;
  56866. }
  56867. };
  56868. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56869. if (this._audioEngine.canUseWebAudio) {
  56870. inputAudioNode.connect(this._webAudioAnalyser);
  56871. this._webAudioAnalyser.connect(outputAudioNode);
  56872. }
  56873. };
  56874. Analyser.prototype.dispose = function () {
  56875. if (this._audioEngine.canUseWebAudio) {
  56876. this._webAudioAnalyser.disconnect();
  56877. }
  56878. };
  56879. return Analyser;
  56880. }());
  56881. BABYLON.Analyser = Analyser;
  56882. })(BABYLON || (BABYLON = {}));
  56883. //# sourceMappingURL=babylon.analyser.js.map
  56884. var BABYLON;
  56885. (function (BABYLON) {
  56886. var CubeTexture = /** @class */ (function (_super) {
  56887. __extends(CubeTexture, _super);
  56888. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56889. if (extensions === void 0) { extensions = null; }
  56890. if (noMipmap === void 0) { noMipmap = false; }
  56891. if (files === void 0) { files = null; }
  56892. if (onLoad === void 0) { onLoad = null; }
  56893. if (onError === void 0) { onError = null; }
  56894. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56895. if (prefiltered === void 0) { prefiltered = false; }
  56896. if (forcedExtension === void 0) { forcedExtension = null; }
  56897. var _this = _super.call(this, scene) || this;
  56898. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56899. /**
  56900. * Gets or sets the center of the bounding box associated with the cube texture
  56901. * It must define where the camera used to render the texture was set
  56902. */
  56903. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56904. _this.name = rootUrl;
  56905. _this.url = rootUrl;
  56906. _this._noMipmap = noMipmap;
  56907. _this.hasAlpha = false;
  56908. _this._format = format;
  56909. _this._prefiltered = prefiltered;
  56910. _this.isCube = true;
  56911. _this._textureMatrix = BABYLON.Matrix.Identity();
  56912. if (prefiltered) {
  56913. _this.gammaSpace = false;
  56914. }
  56915. if (!rootUrl && !files) {
  56916. return _this;
  56917. }
  56918. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56919. var lastDot = rootUrl.lastIndexOf(".");
  56920. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56921. var isDDS = (extension === ".dds");
  56922. if (!files) {
  56923. if (!isDDS && !extensions) {
  56924. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56925. }
  56926. files = [];
  56927. if (extensions) {
  56928. for (var index = 0; index < extensions.length; index++) {
  56929. files.push(rootUrl + extensions[index]);
  56930. }
  56931. }
  56932. }
  56933. _this._files = files;
  56934. if (!_this._texture) {
  56935. if (!scene.useDelayedTextureLoading) {
  56936. if (prefiltered) {
  56937. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56938. }
  56939. else {
  56940. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56941. }
  56942. }
  56943. else {
  56944. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56945. }
  56946. }
  56947. else if (onLoad) {
  56948. if (_this._texture.isReady) {
  56949. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56950. }
  56951. else {
  56952. _this._texture.onLoadedObservable.add(onLoad);
  56953. }
  56954. }
  56955. return _this;
  56956. }
  56957. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56958. get: function () {
  56959. return this._boundingBoxSize;
  56960. },
  56961. /**
  56962. * Gets or sets the size of the bounding box associated with the cube texture
  56963. * When defined, the cubemap will switch to local mode
  56964. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56965. * @example https://www.babylonjs-playground.com/#RNASML
  56966. */
  56967. set: function (value) {
  56968. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56969. return;
  56970. }
  56971. this._boundingBoxSize = value;
  56972. var scene = this.getScene();
  56973. if (scene) {
  56974. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56975. }
  56976. },
  56977. enumerable: true,
  56978. configurable: true
  56979. });
  56980. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56981. var rootUrlKey = "";
  56982. files.forEach(function (url) { return rootUrlKey += url; });
  56983. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  56984. };
  56985. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56986. if (forcedExtension === void 0) { forcedExtension = null; }
  56987. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56988. };
  56989. // Methods
  56990. CubeTexture.prototype.delayLoad = function () {
  56991. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56992. return;
  56993. }
  56994. var scene = this.getScene();
  56995. if (!scene) {
  56996. return;
  56997. }
  56998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56999. this._texture = this._getFromCache(this.url, this._noMipmap);
  57000. if (!this._texture) {
  57001. if (this._prefiltered) {
  57002. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57003. }
  57004. else {
  57005. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57006. }
  57007. }
  57008. };
  57009. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57010. return this._textureMatrix;
  57011. };
  57012. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57013. this._textureMatrix = value;
  57014. };
  57015. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57016. var texture = BABYLON.SerializationHelper.Parse(function () {
  57017. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57018. }, parsedTexture, scene);
  57019. // Local Cubemaps
  57020. if (parsedTexture.boundingBoxPosition) {
  57021. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57022. }
  57023. if (parsedTexture.boundingBoxSize) {
  57024. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57025. }
  57026. // Animations
  57027. if (parsedTexture.animations) {
  57028. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57029. var parsedAnimation = parsedTexture.animations[animationIndex];
  57030. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57031. }
  57032. }
  57033. return texture;
  57034. };
  57035. CubeTexture.prototype.clone = function () {
  57036. var _this = this;
  57037. return BABYLON.SerializationHelper.Clone(function () {
  57038. var scene = _this.getScene();
  57039. if (!scene) {
  57040. return _this;
  57041. }
  57042. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57043. }, this);
  57044. };
  57045. return CubeTexture;
  57046. }(BABYLON.BaseTexture));
  57047. BABYLON.CubeTexture = CubeTexture;
  57048. })(BABYLON || (BABYLON = {}));
  57049. //# sourceMappingURL=babylon.cubeTexture.js.map
  57050. var BABYLON;
  57051. (function (BABYLON) {
  57052. var RenderTargetTexture = /** @class */ (function (_super) {
  57053. __extends(RenderTargetTexture, _super);
  57054. /**
  57055. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57056. * or used a shadow, depth texture...
  57057. * @param name The friendly name of the texture
  57058. * @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)
  57059. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57060. * @param generateMipMaps True if mip maps need to be generated after render.
  57061. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57062. * @param type The type of the buffer in the RTT (int, half float, float...)
  57063. * @param isCube True if a cube texture needs to be created
  57064. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57065. * @param generateDepthBuffer True to generate a depth buffer
  57066. * @param generateStencilBuffer True to generate a stencil buffer
  57067. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57068. */
  57069. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57070. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57071. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57072. if (isCube === void 0) { isCube = false; }
  57073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57074. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57075. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57076. if (isMulti === void 0) { isMulti = false; }
  57077. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57078. _this.isCube = isCube;
  57079. /**
  57080. * Use this list to define the list of mesh you want to render.
  57081. */
  57082. _this.renderList = new Array();
  57083. _this.renderParticles = true;
  57084. _this.renderSprites = false;
  57085. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57086. _this.ignoreCameraViewport = false;
  57087. // Events
  57088. /**
  57089. * An event triggered when the texture is unbind.
  57090. * @type {BABYLON.Observable}
  57091. */
  57092. _this.onBeforeBindObservable = new BABYLON.Observable();
  57093. /**
  57094. * An event triggered when the texture is unbind.
  57095. * @type {BABYLON.Observable}
  57096. */
  57097. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57098. /**
  57099. * An event triggered before rendering the texture
  57100. * @type {BABYLON.Observable}
  57101. */
  57102. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57103. /**
  57104. * An event triggered after rendering the texture
  57105. * @type {BABYLON.Observable}
  57106. */
  57107. _this.onAfterRenderObservable = new BABYLON.Observable();
  57108. /**
  57109. * An event triggered after the texture clear
  57110. * @type {BABYLON.Observable}
  57111. */
  57112. _this.onClearObservable = new BABYLON.Observable();
  57113. _this._currentRefreshId = -1;
  57114. _this._refreshRate = 1;
  57115. _this._samples = 1;
  57116. /**
  57117. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57118. * It must define where the camera used to render the texture is set
  57119. */
  57120. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57121. scene = _this.getScene();
  57122. if (!scene) {
  57123. return _this;
  57124. }
  57125. _this._engine = scene.getEngine();
  57126. _this.name = name;
  57127. _this.isRenderTarget = true;
  57128. _this._initialSizeParameter = size;
  57129. _this._processSizeParameter(size);
  57130. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57131. });
  57132. _this._generateMipMaps = generateMipMaps ? true : false;
  57133. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57134. // Rendering groups
  57135. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57136. if (isMulti) {
  57137. return _this;
  57138. }
  57139. _this._renderTargetOptions = {
  57140. generateMipMaps: generateMipMaps,
  57141. type: type,
  57142. samplingMode: samplingMode,
  57143. generateDepthBuffer: generateDepthBuffer,
  57144. generateStencilBuffer: generateStencilBuffer
  57145. };
  57146. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57147. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57148. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57149. }
  57150. if (isCube) {
  57151. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57152. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57153. _this._textureMatrix = BABYLON.Matrix.Identity();
  57154. }
  57155. else {
  57156. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57157. }
  57158. return _this;
  57159. }
  57160. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57161. get: function () {
  57162. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57163. },
  57164. enumerable: true,
  57165. configurable: true
  57166. });
  57167. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57168. get: function () {
  57169. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57170. },
  57171. enumerable: true,
  57172. configurable: true
  57173. });
  57174. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57175. get: function () {
  57176. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57177. },
  57178. enumerable: true,
  57179. configurable: true
  57180. });
  57181. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57182. set: function (callback) {
  57183. if (this._onAfterUnbindObserver) {
  57184. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57185. }
  57186. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57187. },
  57188. enumerable: true,
  57189. configurable: true
  57190. });
  57191. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57192. set: function (callback) {
  57193. if (this._onBeforeRenderObserver) {
  57194. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57195. }
  57196. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57197. },
  57198. enumerable: true,
  57199. configurable: true
  57200. });
  57201. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57202. set: function (callback) {
  57203. if (this._onAfterRenderObserver) {
  57204. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57205. }
  57206. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57207. },
  57208. enumerable: true,
  57209. configurable: true
  57210. });
  57211. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57212. set: function (callback) {
  57213. if (this._onClearObserver) {
  57214. this.onClearObservable.remove(this._onClearObserver);
  57215. }
  57216. this._onClearObserver = this.onClearObservable.add(callback);
  57217. },
  57218. enumerable: true,
  57219. configurable: true
  57220. });
  57221. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57222. get: function () {
  57223. return this._renderTargetOptions;
  57224. },
  57225. enumerable: true,
  57226. configurable: true
  57227. });
  57228. RenderTargetTexture.prototype._onRatioRescale = function () {
  57229. if (this._sizeRatio) {
  57230. this.resize(this._initialSizeParameter);
  57231. }
  57232. };
  57233. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57234. get: function () {
  57235. return this._boundingBoxSize;
  57236. },
  57237. /**
  57238. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57239. * When defined, the cubemap will switch to local mode
  57240. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57241. * @example https://www.babylonjs-playground.com/#RNASML
  57242. */
  57243. set: function (value) {
  57244. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57245. return;
  57246. }
  57247. this._boundingBoxSize = value;
  57248. var scene = this.getScene();
  57249. if (scene) {
  57250. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57251. }
  57252. },
  57253. enumerable: true,
  57254. configurable: true
  57255. });
  57256. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57257. if (size.ratio) {
  57258. this._sizeRatio = size.ratio;
  57259. this._size = {
  57260. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57261. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57262. };
  57263. }
  57264. else {
  57265. this._size = size;
  57266. }
  57267. };
  57268. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57269. get: function () {
  57270. return this._samples;
  57271. },
  57272. set: function (value) {
  57273. if (this._samples === value) {
  57274. return;
  57275. }
  57276. var scene = this.getScene();
  57277. if (!scene) {
  57278. return;
  57279. }
  57280. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57281. },
  57282. enumerable: true,
  57283. configurable: true
  57284. });
  57285. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57286. this._currentRefreshId = -1;
  57287. };
  57288. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57289. get: function () {
  57290. return this._refreshRate;
  57291. },
  57292. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57293. set: function (value) {
  57294. this._refreshRate = value;
  57295. this.resetRefreshCounter();
  57296. },
  57297. enumerable: true,
  57298. configurable: true
  57299. });
  57300. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57301. if (!this._postProcessManager) {
  57302. var scene = this.getScene();
  57303. if (!scene) {
  57304. return;
  57305. }
  57306. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57307. this._postProcesses = new Array();
  57308. }
  57309. this._postProcesses.push(postProcess);
  57310. this._postProcesses[0].autoClear = false;
  57311. };
  57312. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57313. if (!this._postProcesses) {
  57314. return;
  57315. }
  57316. if (dispose) {
  57317. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57318. var postProcess = _a[_i];
  57319. postProcess.dispose();
  57320. }
  57321. }
  57322. this._postProcesses = [];
  57323. };
  57324. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57325. if (!this._postProcesses) {
  57326. return;
  57327. }
  57328. var index = this._postProcesses.indexOf(postProcess);
  57329. if (index === -1) {
  57330. return;
  57331. }
  57332. this._postProcesses.splice(index, 1);
  57333. if (this._postProcesses.length > 0) {
  57334. this._postProcesses[0].autoClear = false;
  57335. }
  57336. };
  57337. RenderTargetTexture.prototype._shouldRender = function () {
  57338. if (this._currentRefreshId === -1) {
  57339. this._currentRefreshId = 1;
  57340. return true;
  57341. }
  57342. if (this.refreshRate === this._currentRefreshId) {
  57343. this._currentRefreshId = 1;
  57344. return true;
  57345. }
  57346. this._currentRefreshId++;
  57347. return false;
  57348. };
  57349. RenderTargetTexture.prototype.getRenderSize = function () {
  57350. if (this._size.width) {
  57351. return this._size.width;
  57352. }
  57353. return this._size;
  57354. };
  57355. RenderTargetTexture.prototype.getRenderWidth = function () {
  57356. if (this._size.width) {
  57357. return this._size.width;
  57358. }
  57359. return this._size;
  57360. };
  57361. RenderTargetTexture.prototype.getRenderHeight = function () {
  57362. if (this._size.width) {
  57363. return this._size.height;
  57364. }
  57365. return this._size;
  57366. };
  57367. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57368. get: function () {
  57369. return true;
  57370. },
  57371. enumerable: true,
  57372. configurable: true
  57373. });
  57374. RenderTargetTexture.prototype.scale = function (ratio) {
  57375. var newSize = this.getRenderSize() * ratio;
  57376. this.resize(newSize);
  57377. };
  57378. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57379. if (this.isCube) {
  57380. return this._textureMatrix;
  57381. }
  57382. return _super.prototype.getReflectionTextureMatrix.call(this);
  57383. };
  57384. RenderTargetTexture.prototype.resize = function (size) {
  57385. this.releaseInternalTexture();
  57386. var scene = this.getScene();
  57387. if (!scene) {
  57388. return;
  57389. }
  57390. this._processSizeParameter(size);
  57391. if (this.isCube) {
  57392. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57393. }
  57394. else {
  57395. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57396. }
  57397. };
  57398. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57399. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57400. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57401. var scene = this.getScene();
  57402. if (!scene) {
  57403. return;
  57404. }
  57405. var engine = scene.getEngine();
  57406. if (this.useCameraPostProcesses !== undefined) {
  57407. useCameraPostProcess = this.useCameraPostProcesses;
  57408. }
  57409. if (this._waitingRenderList) {
  57410. this.renderList = [];
  57411. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57412. var id = this._waitingRenderList[index];
  57413. var mesh_1 = scene.getMeshByID(id);
  57414. if (mesh_1) {
  57415. this.renderList.push(mesh_1);
  57416. }
  57417. }
  57418. delete this._waitingRenderList;
  57419. }
  57420. // Is predicate defined?
  57421. if (this.renderListPredicate) {
  57422. if (this.renderList) {
  57423. this.renderList.splice(0); // Clear previous renderList
  57424. }
  57425. else {
  57426. this.renderList = [];
  57427. }
  57428. var scene = this.getScene();
  57429. if (!scene) {
  57430. return;
  57431. }
  57432. var sceneMeshes = scene.meshes;
  57433. for (var index = 0; index < sceneMeshes.length; index++) {
  57434. var mesh = sceneMeshes[index];
  57435. if (this.renderListPredicate(mesh)) {
  57436. this.renderList.push(mesh);
  57437. }
  57438. }
  57439. }
  57440. this.onBeforeBindObservable.notifyObservers(this);
  57441. // Set custom projection.
  57442. // Needs to be before binding to prevent changing the aspect ratio.
  57443. var camera;
  57444. if (this.activeCamera) {
  57445. camera = this.activeCamera;
  57446. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57447. if (this.activeCamera !== scene.activeCamera) {
  57448. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57449. }
  57450. }
  57451. else {
  57452. camera = scene.activeCamera;
  57453. if (camera) {
  57454. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57455. }
  57456. }
  57457. // Prepare renderingManager
  57458. this._renderingManager.reset();
  57459. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57460. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57461. var sceneRenderId = scene.getRenderId();
  57462. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57463. var mesh = currentRenderList[meshIndex];
  57464. if (mesh) {
  57465. if (!mesh.isReady()) {
  57466. // Reset _currentRefreshId
  57467. this.resetRefreshCounter();
  57468. continue;
  57469. }
  57470. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57471. var isMasked = void 0;
  57472. if (!this.renderList && camera) {
  57473. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57474. }
  57475. else {
  57476. isMasked = false;
  57477. }
  57478. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57479. mesh._activate(sceneRenderId);
  57480. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57481. var subMesh = mesh.subMeshes[subIndex];
  57482. scene._activeIndices.addCount(subMesh.indexCount, false);
  57483. this._renderingManager.dispatch(subMesh, mesh);
  57484. }
  57485. }
  57486. }
  57487. }
  57488. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57489. var particleSystem = scene.particleSystems[particleIndex];
  57490. var emitter = particleSystem.emitter;
  57491. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57492. continue;
  57493. }
  57494. if (currentRenderList.indexOf(emitter) >= 0) {
  57495. this._renderingManager.dispatchParticles(particleSystem);
  57496. }
  57497. }
  57498. if (this.isCube) {
  57499. for (var face = 0; face < 6; face++) {
  57500. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57501. scene.incrementRenderId();
  57502. scene.resetCachedMaterial();
  57503. }
  57504. }
  57505. else {
  57506. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57507. }
  57508. this.onAfterUnbindObservable.notifyObservers(this);
  57509. if (scene.activeCamera) {
  57510. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57511. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57512. }
  57513. engine.setViewport(scene.activeCamera.viewport);
  57514. }
  57515. scene.resetCachedMaterial();
  57516. };
  57517. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57518. var minimum = 128;
  57519. var x = renderDimension * scale;
  57520. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57521. // Ensure we don't exceed the render dimension (while staying POT)
  57522. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57523. };
  57524. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57525. var _this = this;
  57526. if (!this._texture) {
  57527. return;
  57528. }
  57529. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57530. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57531. });
  57532. };
  57533. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57534. var scene = this.getScene();
  57535. if (!scene) {
  57536. return;
  57537. }
  57538. var engine = scene.getEngine();
  57539. if (!this._texture) {
  57540. return;
  57541. }
  57542. // Bind
  57543. if (this._postProcessManager) {
  57544. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57545. }
  57546. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57547. if (this._texture) {
  57548. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57549. }
  57550. }
  57551. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57552. // Clear
  57553. if (this.onClearObservable.hasObservers()) {
  57554. this.onClearObservable.notifyObservers(engine);
  57555. }
  57556. else {
  57557. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57558. }
  57559. if (!this._doNotChangeAspectRatio) {
  57560. scene.updateTransformMatrix(true);
  57561. }
  57562. // Render
  57563. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57564. if (this._postProcessManager) {
  57565. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57566. }
  57567. else if (useCameraPostProcess) {
  57568. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57569. }
  57570. if (!this._doNotChangeAspectRatio) {
  57571. scene.updateTransformMatrix(true);
  57572. }
  57573. // Dump ?
  57574. if (dumpForDebug) {
  57575. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57576. }
  57577. // Unbind
  57578. if (!this.isCube || faceIndex === 5) {
  57579. if (this.isCube) {
  57580. if (faceIndex === 5) {
  57581. engine.generateMipMapsForCubemap(this._texture);
  57582. }
  57583. }
  57584. this.unbindFrameBuffer(engine, faceIndex);
  57585. }
  57586. else {
  57587. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57588. }
  57589. };
  57590. /**
  57591. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57592. * This allowed control for front to back rendering or reversly depending of the special needs.
  57593. *
  57594. * @param renderingGroupId The rendering group id corresponding to its index
  57595. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57596. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57597. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57598. */
  57599. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57600. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57601. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57602. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57603. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57604. };
  57605. /**
  57606. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57607. *
  57608. * @param renderingGroupId The rendering group id corresponding to its index
  57609. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57610. */
  57611. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57612. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57613. };
  57614. RenderTargetTexture.prototype.clone = function () {
  57615. var textureSize = this.getSize();
  57616. 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);
  57617. // Base texture
  57618. newTexture.hasAlpha = this.hasAlpha;
  57619. newTexture.level = this.level;
  57620. // RenderTarget Texture
  57621. newTexture.coordinatesMode = this.coordinatesMode;
  57622. if (this.renderList) {
  57623. newTexture.renderList = this.renderList.slice(0);
  57624. }
  57625. return newTexture;
  57626. };
  57627. RenderTargetTexture.prototype.serialize = function () {
  57628. if (!this.name) {
  57629. return null;
  57630. }
  57631. var serializationObject = _super.prototype.serialize.call(this);
  57632. serializationObject.renderTargetSize = this.getRenderSize();
  57633. serializationObject.renderList = [];
  57634. if (this.renderList) {
  57635. for (var index = 0; index < this.renderList.length; index++) {
  57636. serializationObject.renderList.push(this.renderList[index].id);
  57637. }
  57638. }
  57639. return serializationObject;
  57640. };
  57641. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57642. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57643. var objBuffer = this.getInternalTexture();
  57644. var scene = this.getScene();
  57645. if (objBuffer && scene) {
  57646. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57647. }
  57648. };
  57649. RenderTargetTexture.prototype.dispose = function () {
  57650. if (this._postProcessManager) {
  57651. this._postProcessManager.dispose();
  57652. this._postProcessManager = null;
  57653. }
  57654. this.clearPostProcesses(true);
  57655. if (this._resizeObserver) {
  57656. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57657. this._resizeObserver = null;
  57658. }
  57659. this.renderList = null;
  57660. // Remove from custom render targets
  57661. var scene = this.getScene();
  57662. if (!scene) {
  57663. return;
  57664. }
  57665. var index = scene.customRenderTargets.indexOf(this);
  57666. if (index >= 0) {
  57667. scene.customRenderTargets.splice(index, 1);
  57668. }
  57669. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57670. var camera = _a[_i];
  57671. index = camera.customRenderTargets.indexOf(this);
  57672. if (index >= 0) {
  57673. camera.customRenderTargets.splice(index, 1);
  57674. }
  57675. }
  57676. _super.prototype.dispose.call(this);
  57677. };
  57678. RenderTargetTexture.prototype._rebuild = function () {
  57679. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57680. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57681. }
  57682. if (this._postProcessManager) {
  57683. this._postProcessManager._rebuild();
  57684. }
  57685. };
  57686. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57687. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57688. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57689. return RenderTargetTexture;
  57690. }(BABYLON.Texture));
  57691. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57692. })(BABYLON || (BABYLON = {}));
  57693. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57694. var BABYLON;
  57695. (function (BABYLON) {
  57696. ;
  57697. var MultiRenderTarget = /** @class */ (function (_super) {
  57698. __extends(MultiRenderTarget, _super);
  57699. function MultiRenderTarget(name, size, count, scene, options) {
  57700. var _this = this;
  57701. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57702. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57703. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57704. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57705. _this._engine = scene.getEngine();
  57706. if (!_this.isSupported) {
  57707. _this.dispose();
  57708. return;
  57709. }
  57710. var types = [];
  57711. var samplingModes = [];
  57712. for (var i = 0; i < count; i++) {
  57713. if (options && options.types && options.types[i] !== undefined) {
  57714. types.push(options.types[i]);
  57715. }
  57716. else {
  57717. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57718. }
  57719. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57720. samplingModes.push(options.samplingModes[i]);
  57721. }
  57722. else {
  57723. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57724. }
  57725. }
  57726. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57727. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57728. _this._size = size;
  57729. _this._multiRenderTargetOptions = {
  57730. samplingModes: samplingModes,
  57731. generateMipMaps: generateMipMaps,
  57732. generateDepthBuffer: generateDepthBuffer,
  57733. generateStencilBuffer: generateStencilBuffer,
  57734. generateDepthTexture: generateDepthTexture,
  57735. types: types,
  57736. textureCount: count
  57737. };
  57738. _this._createInternalTextures();
  57739. _this._createTextures();
  57740. return _this;
  57741. }
  57742. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57743. get: function () {
  57744. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57745. },
  57746. enumerable: true,
  57747. configurable: true
  57748. });
  57749. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57750. get: function () {
  57751. return this._textures;
  57752. },
  57753. enumerable: true,
  57754. configurable: true
  57755. });
  57756. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57757. get: function () {
  57758. return this._textures[this._textures.length - 1];
  57759. },
  57760. enumerable: true,
  57761. configurable: true
  57762. });
  57763. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57764. set: function (wrap) {
  57765. if (this._textures) {
  57766. for (var i = 0; i < this._textures.length; i++) {
  57767. this._textures[i].wrapU = wrap;
  57768. }
  57769. }
  57770. },
  57771. enumerable: true,
  57772. configurable: true
  57773. });
  57774. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57775. set: function (wrap) {
  57776. if (this._textures) {
  57777. for (var i = 0; i < this._textures.length; i++) {
  57778. this._textures[i].wrapV = wrap;
  57779. }
  57780. }
  57781. },
  57782. enumerable: true,
  57783. configurable: true
  57784. });
  57785. MultiRenderTarget.prototype._rebuild = function () {
  57786. this.releaseInternalTextures();
  57787. this._createInternalTextures();
  57788. for (var i = 0; i < this._internalTextures.length; i++) {
  57789. var texture = this._textures[i];
  57790. texture._texture = this._internalTextures[i];
  57791. }
  57792. // Keeps references to frame buffer and stencil/depth buffer
  57793. this._texture = this._internalTextures[0];
  57794. };
  57795. MultiRenderTarget.prototype._createInternalTextures = function () {
  57796. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57797. };
  57798. MultiRenderTarget.prototype._createTextures = function () {
  57799. this._textures = [];
  57800. for (var i = 0; i < this._internalTextures.length; i++) {
  57801. var texture = new BABYLON.Texture(null, this.getScene());
  57802. texture._texture = this._internalTextures[i];
  57803. this._textures.push(texture);
  57804. }
  57805. // Keeps references to frame buffer and stencil/depth buffer
  57806. this._texture = this._internalTextures[0];
  57807. };
  57808. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57809. get: function () {
  57810. return this._samples;
  57811. },
  57812. set: function (value) {
  57813. if (this._samples === value) {
  57814. return;
  57815. }
  57816. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57817. },
  57818. enumerable: true,
  57819. configurable: true
  57820. });
  57821. MultiRenderTarget.prototype.resize = function (size) {
  57822. this.releaseInternalTextures();
  57823. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57824. this._createInternalTextures();
  57825. };
  57826. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57827. var _this = this;
  57828. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57829. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57830. });
  57831. };
  57832. MultiRenderTarget.prototype.dispose = function () {
  57833. this.releaseInternalTextures();
  57834. _super.prototype.dispose.call(this);
  57835. };
  57836. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57837. if (!this._internalTextures) {
  57838. return;
  57839. }
  57840. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57841. if (this._internalTextures[i] !== undefined) {
  57842. this._internalTextures[i].dispose();
  57843. this._internalTextures.splice(i, 1);
  57844. }
  57845. }
  57846. };
  57847. return MultiRenderTarget;
  57848. }(BABYLON.RenderTargetTexture));
  57849. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57850. })(BABYLON || (BABYLON = {}));
  57851. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57852. var BABYLON;
  57853. (function (BABYLON) {
  57854. var MirrorTexture = /** @class */ (function (_super) {
  57855. __extends(MirrorTexture, _super);
  57856. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57857. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57859. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57860. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57861. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57862. _this._transformMatrix = BABYLON.Matrix.Zero();
  57863. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57864. _this._adaptiveBlurKernel = 0;
  57865. _this._blurKernelX = 0;
  57866. _this._blurKernelY = 0;
  57867. _this._blurRatio = 1.0;
  57868. _this.ignoreCameraViewport = true;
  57869. _this.onBeforeRenderObservable.add(function () {
  57870. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57871. _this._savedViewMatrix = scene.getViewMatrix();
  57872. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57873. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57874. scene.clipPlane = _this.mirrorPlane;
  57875. scene.getEngine().cullBackFaces = false;
  57876. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57877. });
  57878. _this.onAfterRenderObservable.add(function () {
  57879. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57880. scene.getEngine().cullBackFaces = true;
  57881. scene._mirroredCameraPosition = null;
  57882. delete scene.clipPlane;
  57883. });
  57884. return _this;
  57885. }
  57886. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57887. get: function () {
  57888. return this._blurRatio;
  57889. },
  57890. set: function (value) {
  57891. if (this._blurRatio === value) {
  57892. return;
  57893. }
  57894. this._blurRatio = value;
  57895. this._preparePostProcesses();
  57896. },
  57897. enumerable: true,
  57898. configurable: true
  57899. });
  57900. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57901. set: function (value) {
  57902. this._adaptiveBlurKernel = value;
  57903. this._autoComputeBlurKernel();
  57904. },
  57905. enumerable: true,
  57906. configurable: true
  57907. });
  57908. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57909. set: function (value) {
  57910. this.blurKernelX = value;
  57911. this.blurKernelY = value;
  57912. },
  57913. enumerable: true,
  57914. configurable: true
  57915. });
  57916. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57917. get: function () {
  57918. return this._blurKernelX;
  57919. },
  57920. set: function (value) {
  57921. if (this._blurKernelX === value) {
  57922. return;
  57923. }
  57924. this._blurKernelX = value;
  57925. this._preparePostProcesses();
  57926. },
  57927. enumerable: true,
  57928. configurable: true
  57929. });
  57930. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57931. get: function () {
  57932. return this._blurKernelY;
  57933. },
  57934. set: function (value) {
  57935. if (this._blurKernelY === value) {
  57936. return;
  57937. }
  57938. this._blurKernelY = value;
  57939. this._preparePostProcesses();
  57940. },
  57941. enumerable: true,
  57942. configurable: true
  57943. });
  57944. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57945. var engine = this.getScene().getEngine();
  57946. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57947. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57948. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57949. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57950. };
  57951. MirrorTexture.prototype._onRatioRescale = function () {
  57952. if (this._sizeRatio) {
  57953. this.resize(this._initialSizeParameter);
  57954. if (!this._adaptiveBlurKernel) {
  57955. this._preparePostProcesses();
  57956. }
  57957. }
  57958. if (this._adaptiveBlurKernel) {
  57959. this._autoComputeBlurKernel();
  57960. }
  57961. };
  57962. MirrorTexture.prototype._preparePostProcesses = function () {
  57963. this.clearPostProcesses(true);
  57964. if (this._blurKernelX && this._blurKernelY) {
  57965. var engine = this.getScene().getEngine();
  57966. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57967. 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);
  57968. this._blurX.autoClear = false;
  57969. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57970. this._blurX.inputTexture = this._texture;
  57971. }
  57972. else {
  57973. this._blurX.alwaysForcePOT = true;
  57974. }
  57975. 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);
  57976. this._blurY.autoClear = false;
  57977. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57978. this.addPostProcess(this._blurX);
  57979. this.addPostProcess(this._blurY);
  57980. }
  57981. else {
  57982. if (this._blurY) {
  57983. this.removePostProcess(this._blurY);
  57984. this._blurY.dispose();
  57985. this._blurY = null;
  57986. }
  57987. if (this._blurX) {
  57988. this.removePostProcess(this._blurX);
  57989. this._blurX.dispose();
  57990. this._blurX = null;
  57991. }
  57992. }
  57993. };
  57994. MirrorTexture.prototype.clone = function () {
  57995. var scene = this.getScene();
  57996. if (!scene) {
  57997. return this;
  57998. }
  57999. var textureSize = this.getSize();
  58000. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58001. // Base texture
  58002. newTexture.hasAlpha = this.hasAlpha;
  58003. newTexture.level = this.level;
  58004. // Mirror Texture
  58005. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58006. if (this.renderList) {
  58007. newTexture.renderList = this.renderList.slice(0);
  58008. }
  58009. return newTexture;
  58010. };
  58011. MirrorTexture.prototype.serialize = function () {
  58012. if (!this.name) {
  58013. return null;
  58014. }
  58015. var serializationObject = _super.prototype.serialize.call(this);
  58016. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58017. return serializationObject;
  58018. };
  58019. return MirrorTexture;
  58020. }(BABYLON.RenderTargetTexture));
  58021. BABYLON.MirrorTexture = MirrorTexture;
  58022. })(BABYLON || (BABYLON = {}));
  58023. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58024. var BABYLON;
  58025. (function (BABYLON) {
  58026. /**
  58027. * Creates a refraction texture used by refraction channel of the standard material.
  58028. * @param name the texture name
  58029. * @param size size of the underlying texture
  58030. * @param scene root scene
  58031. */
  58032. var RefractionTexture = /** @class */ (function (_super) {
  58033. __extends(RefractionTexture, _super);
  58034. function RefractionTexture(name, size, scene, generateMipMaps) {
  58035. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58036. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58037. _this.depth = 2.0;
  58038. _this.onBeforeRenderObservable.add(function () {
  58039. scene.clipPlane = _this.refractionPlane;
  58040. });
  58041. _this.onAfterRenderObservable.add(function () {
  58042. delete scene.clipPlane;
  58043. });
  58044. return _this;
  58045. }
  58046. RefractionTexture.prototype.clone = function () {
  58047. var scene = this.getScene();
  58048. if (!scene) {
  58049. return this;
  58050. }
  58051. var textureSize = this.getSize();
  58052. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58053. // Base texture
  58054. newTexture.hasAlpha = this.hasAlpha;
  58055. newTexture.level = this.level;
  58056. // Refraction Texture
  58057. newTexture.refractionPlane = this.refractionPlane.clone();
  58058. if (this.renderList) {
  58059. newTexture.renderList = this.renderList.slice(0);
  58060. }
  58061. newTexture.depth = this.depth;
  58062. return newTexture;
  58063. };
  58064. RefractionTexture.prototype.serialize = function () {
  58065. if (!this.name) {
  58066. return null;
  58067. }
  58068. var serializationObject = _super.prototype.serialize.call(this);
  58069. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58070. serializationObject.depth = this.depth;
  58071. return serializationObject;
  58072. };
  58073. return RefractionTexture;
  58074. }(BABYLON.RenderTargetTexture));
  58075. BABYLON.RefractionTexture = RefractionTexture;
  58076. })(BABYLON || (BABYLON = {}));
  58077. //# sourceMappingURL=babylon.refractionTexture.js.map
  58078. var BABYLON;
  58079. (function (BABYLON) {
  58080. var DynamicTexture = /** @class */ (function (_super) {
  58081. __extends(DynamicTexture, _super);
  58082. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58083. if (scene === void 0) { scene = null; }
  58084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58085. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58086. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58087. _this.name = name;
  58088. _this._engine = _this.getScene().getEngine();
  58089. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58090. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58091. _this._generateMipMaps = generateMipMaps;
  58092. if (options.getContext) {
  58093. _this._canvas = options;
  58094. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58095. }
  58096. else {
  58097. _this._canvas = document.createElement("canvas");
  58098. if (options.width) {
  58099. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58100. }
  58101. else {
  58102. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58103. }
  58104. }
  58105. var textureSize = _this.getSize();
  58106. _this._canvas.width = textureSize.width;
  58107. _this._canvas.height = textureSize.height;
  58108. _this._context = _this._canvas.getContext("2d");
  58109. return _this;
  58110. }
  58111. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58112. get: function () {
  58113. return true;
  58114. },
  58115. enumerable: true,
  58116. configurable: true
  58117. });
  58118. DynamicTexture.prototype._recreate = function (textureSize) {
  58119. this._canvas.width = textureSize.width;
  58120. this._canvas.height = textureSize.height;
  58121. this.releaseInternalTexture();
  58122. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58123. };
  58124. DynamicTexture.prototype.scale = function (ratio) {
  58125. var textureSize = this.getSize();
  58126. textureSize.width *= ratio;
  58127. textureSize.height *= ratio;
  58128. this._recreate(textureSize);
  58129. };
  58130. DynamicTexture.prototype.scaleTo = function (width, height) {
  58131. var textureSize = this.getSize();
  58132. textureSize.width = width;
  58133. textureSize.height = height;
  58134. this._recreate(textureSize);
  58135. };
  58136. DynamicTexture.prototype.getContext = function () {
  58137. return this._context;
  58138. };
  58139. DynamicTexture.prototype.clear = function () {
  58140. var size = this.getSize();
  58141. this._context.fillRect(0, 0, size.width, size.height);
  58142. };
  58143. DynamicTexture.prototype.update = function (invertY) {
  58144. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58145. };
  58146. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58147. if (update === void 0) { update = true; }
  58148. var size = this.getSize();
  58149. if (clearColor) {
  58150. this._context.fillStyle = clearColor;
  58151. this._context.fillRect(0, 0, size.width, size.height);
  58152. }
  58153. this._context.font = font;
  58154. if (x === null || x === undefined) {
  58155. var textSize = this._context.measureText(text);
  58156. x = (size.width - textSize.width) / 2;
  58157. }
  58158. if (y === null || y === undefined) {
  58159. var fontSize = parseInt((font.replace(/\D/g, '')));
  58160. ;
  58161. y = (size.height / 2) + (fontSize / 3.65);
  58162. }
  58163. this._context.fillStyle = color;
  58164. this._context.fillText(text, x, y);
  58165. if (update) {
  58166. this.update(invertY);
  58167. }
  58168. };
  58169. DynamicTexture.prototype.clone = function () {
  58170. var scene = this.getScene();
  58171. if (!scene) {
  58172. return this;
  58173. }
  58174. var textureSize = this.getSize();
  58175. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58176. // Base texture
  58177. newTexture.hasAlpha = this.hasAlpha;
  58178. newTexture.level = this.level;
  58179. // Dynamic Texture
  58180. newTexture.wrapU = this.wrapU;
  58181. newTexture.wrapV = this.wrapV;
  58182. return newTexture;
  58183. };
  58184. DynamicTexture.prototype._rebuild = function () {
  58185. this.update();
  58186. };
  58187. return DynamicTexture;
  58188. }(BABYLON.Texture));
  58189. BABYLON.DynamicTexture = DynamicTexture;
  58190. })(BABYLON || (BABYLON = {}));
  58191. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58192. var BABYLON;
  58193. (function (BABYLON) {
  58194. var VideoTexture = /** @class */ (function (_super) {
  58195. __extends(VideoTexture, _super);
  58196. /**
  58197. * Creates a video texture.
  58198. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58199. * @param {string | null} name optional name, will detect from video source, if not defined
  58200. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58201. * @param {BABYLON.Scene} scene is obviously the current scene.
  58202. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58203. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58204. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58205. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58206. */
  58207. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58208. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58209. if (invertY === void 0) { invertY = false; }
  58210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58211. if (settings === void 0) { settings = {
  58212. autoPlay: true,
  58213. loop: true,
  58214. autoUpdateTexture: true,
  58215. }; }
  58216. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58217. _this._createInternalTexture = function () {
  58218. if (_this._texture != null) {
  58219. return;
  58220. }
  58221. if (!_this._engine.needPOTTextures ||
  58222. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58223. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58224. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58225. }
  58226. else {
  58227. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58228. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58229. _this._generateMipMaps = false;
  58230. }
  58231. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58232. _this._texture.isReady = true;
  58233. _this._updateInternalTexture();
  58234. };
  58235. _this.reset = function () {
  58236. if (_this._texture == null) {
  58237. return;
  58238. }
  58239. _this._texture.dispose();
  58240. _this._texture = null;
  58241. };
  58242. _this._updateInternalTexture = function (e) {
  58243. if (_this._texture == null || !_this._texture.isReady) {
  58244. return;
  58245. }
  58246. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58247. return;
  58248. }
  58249. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58250. };
  58251. _this._engine = _this.getScene().getEngine();
  58252. _this._generateMipMaps = generateMipMaps;
  58253. _this._samplingMode = samplingMode;
  58254. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58255. _this.name = name || _this._getName(src);
  58256. _this.video = _this._getVideo(src);
  58257. if (settings.autoPlay !== undefined) {
  58258. _this.video.autoplay = settings.autoPlay;
  58259. }
  58260. if (settings.loop !== undefined) {
  58261. _this.video.loop = settings.loop;
  58262. }
  58263. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58264. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58265. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58266. _this.video.addEventListener("emptied", _this.reset);
  58267. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58268. _this._createInternalTexture();
  58269. }
  58270. return _this;
  58271. }
  58272. VideoTexture.prototype._getName = function (src) {
  58273. if (src instanceof HTMLVideoElement) {
  58274. return src.currentSrc;
  58275. }
  58276. if (typeof src === "object") {
  58277. return src.toString();
  58278. }
  58279. return src;
  58280. };
  58281. ;
  58282. VideoTexture.prototype._getVideo = function (src) {
  58283. if (src instanceof HTMLVideoElement) {
  58284. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58285. return src;
  58286. }
  58287. var video = document.createElement("video");
  58288. if (typeof src === "string") {
  58289. BABYLON.Tools.SetCorsBehavior(src, video);
  58290. video.src = src;
  58291. }
  58292. else {
  58293. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58294. src.forEach(function (url) {
  58295. var source = document.createElement("source");
  58296. source.src = url;
  58297. video.appendChild(source);
  58298. });
  58299. }
  58300. return video;
  58301. };
  58302. ;
  58303. /**
  58304. * Internal method to initiate `update`.
  58305. */
  58306. VideoTexture.prototype._rebuild = function () {
  58307. this.update();
  58308. };
  58309. /**
  58310. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58311. */
  58312. VideoTexture.prototype.update = function () {
  58313. if (!this.autoUpdateTexture) {
  58314. // Expecting user to call `updateTexture` manually
  58315. return;
  58316. }
  58317. this.updateTexture(true);
  58318. };
  58319. /**
  58320. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58321. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58322. */
  58323. VideoTexture.prototype.updateTexture = function (isVisible) {
  58324. if (!isVisible) {
  58325. return;
  58326. }
  58327. if (this.video.paused) {
  58328. return;
  58329. }
  58330. this._updateInternalTexture();
  58331. };
  58332. /**
  58333. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58334. * @param url New url.
  58335. */
  58336. VideoTexture.prototype.updateURL = function (url) {
  58337. this.video.src = url;
  58338. };
  58339. VideoTexture.prototype.dispose = function () {
  58340. _super.prototype.dispose.call(this);
  58341. this.video.removeEventListener("canplay", this._createInternalTexture);
  58342. this.video.removeEventListener("paused", this._updateInternalTexture);
  58343. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58344. this.video.removeEventListener("emptied", this.reset);
  58345. this.video.pause();
  58346. };
  58347. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58348. var video = document.createElement("video");
  58349. var constraintsDeviceId;
  58350. if (constraints && constraints.deviceId) {
  58351. constraintsDeviceId = {
  58352. exact: constraints.deviceId,
  58353. };
  58354. }
  58355. navigator.getUserMedia =
  58356. navigator.getUserMedia ||
  58357. navigator.webkitGetUserMedia ||
  58358. navigator.mozGetUserMedia ||
  58359. navigator.msGetUserMedia;
  58360. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58361. if (navigator.getUserMedia) {
  58362. navigator.getUserMedia({
  58363. video: {
  58364. deviceId: constraintsDeviceId,
  58365. width: {
  58366. min: (constraints && constraints.minWidth) || 256,
  58367. max: (constraints && constraints.maxWidth) || 640,
  58368. },
  58369. height: {
  58370. min: (constraints && constraints.minHeight) || 256,
  58371. max: (constraints && constraints.maxHeight) || 480,
  58372. },
  58373. },
  58374. }, function (stream) {
  58375. if (video.mozSrcObject !== undefined) {
  58376. // hack for Firefox < 19
  58377. video.mozSrcObject = stream;
  58378. }
  58379. else {
  58380. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58381. }
  58382. video.play();
  58383. if (onReady) {
  58384. onReady(new VideoTexture("video", video, scene, true, true));
  58385. }
  58386. }, function (e) {
  58387. BABYLON.Tools.Error(e.name);
  58388. });
  58389. }
  58390. };
  58391. return VideoTexture;
  58392. }(BABYLON.Texture));
  58393. BABYLON.VideoTexture = VideoTexture;
  58394. })(BABYLON || (BABYLON = {}));
  58395. //# sourceMappingURL=babylon.videoTexture.js.map
  58396. var BABYLON;
  58397. (function (BABYLON) {
  58398. var RawTexture = /** @class */ (function (_super) {
  58399. __extends(RawTexture, _super);
  58400. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58401. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58402. if (invertY === void 0) { invertY = false; }
  58403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58404. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58405. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58406. _this.format = format;
  58407. _this._engine = scene.getEngine();
  58408. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58409. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58410. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58411. return _this;
  58412. }
  58413. RawTexture.prototype.update = function (data) {
  58414. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58415. };
  58416. // Statics
  58417. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58418. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58419. if (invertY === void 0) { invertY = false; }
  58420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58421. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58422. };
  58423. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58424. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58425. if (invertY === void 0) { invertY = false; }
  58426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58427. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58428. };
  58429. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58430. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58431. if (invertY === void 0) { invertY = false; }
  58432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58433. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58434. };
  58435. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58437. if (invertY === void 0) { invertY = false; }
  58438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58439. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58440. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58441. };
  58442. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58443. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58444. if (invertY === void 0) { invertY = false; }
  58445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58446. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58447. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58448. };
  58449. return RawTexture;
  58450. }(BABYLON.Texture));
  58451. BABYLON.RawTexture = RawTexture;
  58452. })(BABYLON || (BABYLON = {}));
  58453. //# sourceMappingURL=babylon.rawTexture.js.map
  58454. var BABYLON;
  58455. (function (BABYLON) {
  58456. /**
  58457. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58458. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58459. */
  58460. var PostProcess = /** @class */ (function () {
  58461. /**
  58462. * Creates a new instance of @see PostProcess
  58463. * @param name The name of the PostProcess.
  58464. * @param fragmentUrl The url of the fragment shader to be used.
  58465. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58466. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58467. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58468. * @param camera The camera to apply the render pass to.
  58469. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58470. * @param engine The engine which the post process will be applied. (default: current engine)
  58471. * @param reusable If the post process can be reused on the same frame. (default: false)
  58472. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58473. * @param textureType Type of textures used when performing the post process. (default: 0)
  58474. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58475. * @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
  58476. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58477. */
  58478. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58480. if (defines === void 0) { defines = null; }
  58481. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58482. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58483. if (blockCompilation === void 0) { blockCompilation = false; }
  58484. this.name = name;
  58485. /**
  58486. * Width of the texture to apply the post process on
  58487. */
  58488. this.width = -1;
  58489. /**
  58490. * Height of the texture to apply the post process on
  58491. */
  58492. this.height = -1;
  58493. /**
  58494. * If the buffer needs to be cleared before applying the post process. (default: true)
  58495. * Should be set to false if shader will overwrite all previous pixels.
  58496. */
  58497. this.autoClear = true;
  58498. /**
  58499. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58500. */
  58501. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58502. /**
  58503. * Animations to be used for the post processing
  58504. */
  58505. this.animations = new Array();
  58506. /**
  58507. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58508. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58509. */
  58510. this.enablePixelPerfectMode = false;
  58511. /**
  58512. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58513. */
  58514. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58515. /**
  58516. * Force textures to be a power of two (default: false)
  58517. */
  58518. this.alwaysForcePOT = false;
  58519. /**
  58520. * Number of sample textures (default: 1)
  58521. */
  58522. this.samples = 1;
  58523. /**
  58524. * Modify the scale of the post process to be the same as the viewport (default: false)
  58525. */
  58526. this.adaptScaleToCurrentViewport = false;
  58527. this._reusable = false;
  58528. /**
  58529. * Smart array of input and output textures for the post process.
  58530. */
  58531. this._textures = new BABYLON.SmartArray(2);
  58532. /**
  58533. * The index in _textures that corresponds to the output texture.
  58534. */
  58535. this._currentRenderTextureInd = 0;
  58536. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58537. this._texelSize = BABYLON.Vector2.Zero();
  58538. // Events
  58539. /**
  58540. * An event triggered when the postprocess is activated.
  58541. * @type {BABYLON.Observable}
  58542. */
  58543. this.onActivateObservable = new BABYLON.Observable();
  58544. /**
  58545. * An event triggered when the postprocess changes its size.
  58546. * @type {BABYLON.Observable}
  58547. */
  58548. this.onSizeChangedObservable = new BABYLON.Observable();
  58549. /**
  58550. * An event triggered when the postprocess applies its effect.
  58551. * @type {BABYLON.Observable}
  58552. */
  58553. this.onApplyObservable = new BABYLON.Observable();
  58554. /**
  58555. * An event triggered before rendering the postprocess
  58556. * @type {BABYLON.Observable}
  58557. */
  58558. this.onBeforeRenderObservable = new BABYLON.Observable();
  58559. /**
  58560. * An event triggered after rendering the postprocess
  58561. * @type {BABYLON.Observable}
  58562. */
  58563. this.onAfterRenderObservable = new BABYLON.Observable();
  58564. if (camera != null) {
  58565. this._camera = camera;
  58566. this._scene = camera.getScene();
  58567. camera.attachPostProcess(this);
  58568. this._engine = this._scene.getEngine();
  58569. this._scene.postProcesses.push(this);
  58570. }
  58571. else if (engine) {
  58572. this._engine = engine;
  58573. this._engine.postProcesses.push(this);
  58574. }
  58575. this._options = options;
  58576. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58577. this._reusable = reusable || false;
  58578. this._textureType = textureType;
  58579. this._samplers = samplers || [];
  58580. this._samplers.push("textureSampler");
  58581. this._fragmentUrl = fragmentUrl;
  58582. this._vertexUrl = vertexUrl;
  58583. this._parameters = parameters || [];
  58584. this._parameters.push("scale");
  58585. this._indexParameters = indexParameters;
  58586. if (!blockCompilation) {
  58587. this.updateEffect(defines);
  58588. }
  58589. }
  58590. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58591. /**
  58592. * A function that is added to the onActivateObservable
  58593. */
  58594. set: function (callback) {
  58595. if (this._onActivateObserver) {
  58596. this.onActivateObservable.remove(this._onActivateObserver);
  58597. }
  58598. if (callback) {
  58599. this._onActivateObserver = this.onActivateObservable.add(callback);
  58600. }
  58601. },
  58602. enumerable: true,
  58603. configurable: true
  58604. });
  58605. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58606. /**
  58607. * A function that is added to the onSizeChangedObservable
  58608. */
  58609. set: function (callback) {
  58610. if (this._onSizeChangedObserver) {
  58611. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58612. }
  58613. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58614. },
  58615. enumerable: true,
  58616. configurable: true
  58617. });
  58618. Object.defineProperty(PostProcess.prototype, "onApply", {
  58619. /**
  58620. * A function that is added to the onApplyObservable
  58621. */
  58622. set: function (callback) {
  58623. if (this._onApplyObserver) {
  58624. this.onApplyObservable.remove(this._onApplyObserver);
  58625. }
  58626. this._onApplyObserver = this.onApplyObservable.add(callback);
  58627. },
  58628. enumerable: true,
  58629. configurable: true
  58630. });
  58631. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58632. /**
  58633. * A function that is added to the onBeforeRenderObservable
  58634. */
  58635. set: function (callback) {
  58636. if (this._onBeforeRenderObserver) {
  58637. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58638. }
  58639. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58640. },
  58641. enumerable: true,
  58642. configurable: true
  58643. });
  58644. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58645. /**
  58646. * A function that is added to the onAfterRenderObservable
  58647. */
  58648. set: function (callback) {
  58649. if (this._onAfterRenderObserver) {
  58650. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58651. }
  58652. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58658. /**
  58659. * 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
  58660. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58661. */
  58662. get: function () {
  58663. return this._textures.data[this._currentRenderTextureInd];
  58664. },
  58665. set: function (value) {
  58666. this._forcedOutputTexture = value;
  58667. },
  58668. enumerable: true,
  58669. configurable: true
  58670. });
  58671. /**
  58672. * Gets the camera which post process is applied to.
  58673. * @returns The camera the post process is applied to.
  58674. */
  58675. PostProcess.prototype.getCamera = function () {
  58676. return this._camera;
  58677. };
  58678. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58679. /**
  58680. * Gets the texel size of the postprocess.
  58681. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58682. */
  58683. get: function () {
  58684. if (this._shareOutputWithPostProcess) {
  58685. return this._shareOutputWithPostProcess.texelSize;
  58686. }
  58687. if (this._forcedOutputTexture) {
  58688. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58689. }
  58690. return this._texelSize;
  58691. },
  58692. enumerable: true,
  58693. configurable: true
  58694. });
  58695. /**
  58696. * Gets the engine which this post process belongs to.
  58697. * @returns The engine the post process was enabled with.
  58698. */
  58699. PostProcess.prototype.getEngine = function () {
  58700. return this._engine;
  58701. };
  58702. /**
  58703. * The effect that is created when initializing the post process.
  58704. * @returns The created effect corrisponding the the postprocess.
  58705. */
  58706. PostProcess.prototype.getEffect = function () {
  58707. return this._effect;
  58708. };
  58709. /**
  58710. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58711. * @param postProcess The post process to share the output with.
  58712. * @returns This post process.
  58713. */
  58714. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58715. this._disposeTextures();
  58716. this._shareOutputWithPostProcess = postProcess;
  58717. return this;
  58718. };
  58719. /**
  58720. * Updates the effect with the current post process compile time values and recompiles the shader.
  58721. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58722. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58723. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58724. * @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
  58725. * @param onCompiled Called when the shader has been compiled.
  58726. * @param onError Called if there is an error when compiling a shader.
  58727. */
  58728. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58729. if (defines === void 0) { defines = null; }
  58730. if (uniforms === void 0) { uniforms = null; }
  58731. if (samplers === void 0) { samplers = null; }
  58732. 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);
  58733. };
  58734. /**
  58735. * The post process is reusable if it can be used multiple times within one frame.
  58736. * @returns If the post process is reusable
  58737. */
  58738. PostProcess.prototype.isReusable = function () {
  58739. return this._reusable;
  58740. };
  58741. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58742. PostProcess.prototype.markTextureDirty = function () {
  58743. this.width = -1;
  58744. };
  58745. /**
  58746. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58747. * 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.
  58748. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58749. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58750. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58751. */
  58752. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58753. var _this = this;
  58754. if (sourceTexture === void 0) { sourceTexture = null; }
  58755. camera = camera || this._camera;
  58756. var scene = camera.getScene();
  58757. var engine = scene.getEngine();
  58758. var maxSize = engine.getCaps().maxTextureSize;
  58759. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58760. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58761. // 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
  58762. var webVRCamera = camera.parent;
  58763. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  58764. requiredWidth /= 2;
  58765. }
  58766. var desiredWidth = (this._options.width || requiredWidth);
  58767. var desiredHeight = this._options.height || requiredHeight;
  58768. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58769. if (this.adaptScaleToCurrentViewport) {
  58770. var currentViewport = engine.currentViewport;
  58771. if (currentViewport) {
  58772. desiredWidth *= currentViewport.width;
  58773. desiredHeight *= currentViewport.height;
  58774. }
  58775. }
  58776. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58777. if (!this._options.width) {
  58778. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58779. }
  58780. if (!this._options.height) {
  58781. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58782. }
  58783. }
  58784. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58785. if (this._textures.length > 0) {
  58786. for (var i = 0; i < this._textures.length; i++) {
  58787. this._engine._releaseTexture(this._textures.data[i]);
  58788. }
  58789. this._textures.reset();
  58790. }
  58791. this.width = desiredWidth;
  58792. this.height = desiredHeight;
  58793. var textureSize = { width: this.width, height: this.height };
  58794. var textureOptions = {
  58795. generateMipMaps: false,
  58796. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58797. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58798. samplingMode: this.renderTargetSamplingMode,
  58799. type: this._textureType
  58800. };
  58801. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58802. if (this._reusable) {
  58803. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58804. }
  58805. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58806. this.onSizeChangedObservable.notifyObservers(this);
  58807. }
  58808. this._textures.forEach(function (texture) {
  58809. if (texture.samples !== _this.samples) {
  58810. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58811. }
  58812. });
  58813. }
  58814. var target;
  58815. if (this._shareOutputWithPostProcess) {
  58816. target = this._shareOutputWithPostProcess.inputTexture;
  58817. }
  58818. else if (this._forcedOutputTexture) {
  58819. target = this._forcedOutputTexture;
  58820. this.width = this._forcedOutputTexture.width;
  58821. this.height = this._forcedOutputTexture.height;
  58822. }
  58823. else {
  58824. target = this.inputTexture;
  58825. }
  58826. // Bind the input of this post process to be used as the output of the previous post process.
  58827. if (this.enablePixelPerfectMode) {
  58828. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58829. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58830. }
  58831. else {
  58832. this._scaleRatio.copyFromFloats(1, 1);
  58833. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58834. }
  58835. this.onActivateObservable.notifyObservers(camera);
  58836. // Clear
  58837. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58838. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58839. }
  58840. if (this._reusable) {
  58841. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58842. }
  58843. };
  58844. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58845. /**
  58846. * If the post process is supported.
  58847. */
  58848. get: function () {
  58849. return this._effect.isSupported;
  58850. },
  58851. enumerable: true,
  58852. configurable: true
  58853. });
  58854. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58855. /**
  58856. * The aspect ratio of the output texture.
  58857. */
  58858. get: function () {
  58859. if (this._shareOutputWithPostProcess) {
  58860. return this._shareOutputWithPostProcess.aspectRatio;
  58861. }
  58862. if (this._forcedOutputTexture) {
  58863. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58864. }
  58865. return this.width / this.height;
  58866. },
  58867. enumerable: true,
  58868. configurable: true
  58869. });
  58870. /**
  58871. * Get a value indicating if the post-process is ready to be used
  58872. * @returns true if the post-process is ready (shader is compiled)
  58873. */
  58874. PostProcess.prototype.isReady = function () {
  58875. return this._effect && this._effect.isReady();
  58876. };
  58877. /**
  58878. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58879. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58880. */
  58881. PostProcess.prototype.apply = function () {
  58882. // Check
  58883. if (!this._effect || !this._effect.isReady())
  58884. return null;
  58885. // States
  58886. this._engine.enableEffect(this._effect);
  58887. this._engine.setState(false);
  58888. this._engine.setDepthBuffer(false);
  58889. this._engine.setDepthWrite(false);
  58890. // Alpha
  58891. this._engine.setAlphaMode(this.alphaMode);
  58892. if (this.alphaConstants) {
  58893. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58894. }
  58895. // Bind the output texture of the preivous post process as the input to this post process.
  58896. var source;
  58897. if (this._shareOutputWithPostProcess) {
  58898. source = this._shareOutputWithPostProcess.inputTexture;
  58899. }
  58900. else if (this._forcedOutputTexture) {
  58901. source = this._forcedOutputTexture;
  58902. }
  58903. else {
  58904. source = this.inputTexture;
  58905. }
  58906. this._effect._bindTexture("textureSampler", source);
  58907. // Parameters
  58908. this._effect.setVector2("scale", this._scaleRatio);
  58909. this.onApplyObservable.notifyObservers(this._effect);
  58910. return this._effect;
  58911. };
  58912. PostProcess.prototype._disposeTextures = function () {
  58913. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58914. return;
  58915. }
  58916. if (this._textures.length > 0) {
  58917. for (var i = 0; i < this._textures.length; i++) {
  58918. this._engine._releaseTexture(this._textures.data[i]);
  58919. }
  58920. }
  58921. this._textures.dispose();
  58922. };
  58923. /**
  58924. * Disposes the post process.
  58925. * @param camera The camera to dispose the post process on.
  58926. */
  58927. PostProcess.prototype.dispose = function (camera) {
  58928. camera = camera || this._camera;
  58929. this._disposeTextures();
  58930. if (this._scene) {
  58931. var index_1 = this._scene.postProcesses.indexOf(this);
  58932. if (index_1 !== -1) {
  58933. this._scene.postProcesses.splice(index_1, 1);
  58934. }
  58935. }
  58936. else {
  58937. var index_2 = this._engine.postProcesses.indexOf(this);
  58938. if (index_2 !== -1) {
  58939. this._engine.postProcesses.splice(index_2, 1);
  58940. }
  58941. }
  58942. if (!camera) {
  58943. return;
  58944. }
  58945. camera.detachPostProcess(this);
  58946. var index = camera._postProcesses.indexOf(this);
  58947. if (index === 0 && camera._postProcesses.length > 0) {
  58948. this._camera._postProcesses[0].markTextureDirty();
  58949. }
  58950. this.onActivateObservable.clear();
  58951. this.onAfterRenderObservable.clear();
  58952. this.onApplyObservable.clear();
  58953. this.onBeforeRenderObservable.clear();
  58954. this.onSizeChangedObservable.clear();
  58955. };
  58956. return PostProcess;
  58957. }());
  58958. BABYLON.PostProcess = PostProcess;
  58959. })(BABYLON || (BABYLON = {}));
  58960. //# sourceMappingURL=babylon.postProcess.js.map
  58961. var BABYLON;
  58962. (function (BABYLON) {
  58963. var PassPostProcess = /** @class */ (function (_super) {
  58964. __extends(PassPostProcess, _super);
  58965. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58966. if (camera === void 0) { camera = null; }
  58967. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58968. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58969. }
  58970. return PassPostProcess;
  58971. }(BABYLON.PostProcess));
  58972. BABYLON.PassPostProcess = PassPostProcess;
  58973. })(BABYLON || (BABYLON = {}));
  58974. //# sourceMappingURL=babylon.passPostProcess.js.map
  58975. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58976. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58977. s = arguments[i];
  58978. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58979. t[p] = s[p];
  58980. }
  58981. return t;
  58982. };
  58983. var BABYLON;
  58984. (function (BABYLON) {
  58985. /**
  58986. * Default implementation of @see IShadowGenerator.
  58987. * This is the main object responsible of generating shadows in the framework.
  58988. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58989. */
  58990. var ShadowGenerator = /** @class */ (function () {
  58991. /**
  58992. * Creates a ShadowGenerator object.
  58993. * A ShadowGenerator is the required tool to use the shadows.
  58994. * Each light casting shadows needs to use its own ShadowGenerator.
  58995. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58996. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58997. * @param light The light object generating the shadows.
  58998. * @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.
  58999. */
  59000. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59001. this._bias = 0.00005;
  59002. this._blurBoxOffset = 1;
  59003. this._blurScale = 2;
  59004. this._blurKernel = 1;
  59005. this._useKernelBlur = false;
  59006. this._filter = ShadowGenerator.FILTER_NONE;
  59007. this._darkness = 0;
  59008. this._transparencyShadow = false;
  59009. /**
  59010. * Controls the extent to which the shadows fade out at the edge of the frustum
  59011. * Used only by directionals and spots
  59012. */
  59013. this.frustumEdgeFalloff = 0;
  59014. /**
  59015. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59016. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59017. * It might on the other hand introduce peter panning.
  59018. */
  59019. this.forceBackFacesOnly = false;
  59020. this._lightDirection = BABYLON.Vector3.Zero();
  59021. this._viewMatrix = BABYLON.Matrix.Zero();
  59022. this._projectionMatrix = BABYLON.Matrix.Zero();
  59023. this._transformMatrix = BABYLON.Matrix.Zero();
  59024. this._currentFaceIndex = 0;
  59025. this._currentFaceIndexCache = 0;
  59026. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59027. this._mapSize = mapSize;
  59028. this._light = light;
  59029. this._scene = light.getScene();
  59030. light._shadowGenerator = this;
  59031. // Texture type fallback from float to int if not supported.
  59032. var caps = this._scene.getEngine().getCaps();
  59033. if (!useFullFloatFirst) {
  59034. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59035. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59036. }
  59037. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59038. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59039. }
  59040. else {
  59041. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59042. }
  59043. }
  59044. else {
  59045. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59046. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59047. }
  59048. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59049. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59050. }
  59051. else {
  59052. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59053. }
  59054. }
  59055. this._initializeGenerator();
  59056. }
  59057. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59058. /**
  59059. * Shadow generator mode None: no filtering applied.
  59060. */
  59061. get: function () {
  59062. return ShadowGenerator._FILTER_NONE;
  59063. },
  59064. enumerable: true,
  59065. configurable: true
  59066. });
  59067. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59068. /**
  59069. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59070. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59071. */
  59072. get: function () {
  59073. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59079. /**
  59080. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59081. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59082. */
  59083. get: function () {
  59084. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59085. },
  59086. enumerable: true,
  59087. configurable: true
  59088. });
  59089. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59090. /**
  59091. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59092. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59093. */
  59094. get: function () {
  59095. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59096. },
  59097. enumerable: true,
  59098. configurable: true
  59099. });
  59100. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59101. /**
  59102. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59103. * edge artifacts on steep falloff.
  59104. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59105. */
  59106. get: function () {
  59107. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59108. },
  59109. enumerable: true,
  59110. configurable: true
  59111. });
  59112. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59113. /**
  59114. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59115. * edge artifacts on steep falloff.
  59116. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59117. */
  59118. get: function () {
  59119. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59120. },
  59121. enumerable: true,
  59122. configurable: true
  59123. });
  59124. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59125. /**
  59126. * Gets the bias: offset applied on the depth preventing acnea.
  59127. */
  59128. get: function () {
  59129. return this._bias;
  59130. },
  59131. /**
  59132. * Sets the bias: offset applied on the depth preventing acnea.
  59133. */
  59134. set: function (bias) {
  59135. this._bias = bias;
  59136. },
  59137. enumerable: true,
  59138. configurable: true
  59139. });
  59140. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59141. /**
  59142. * Gets the blur box offset: offset applied during the blur pass.
  59143. * Only usefull if useKernelBlur = false
  59144. */
  59145. get: function () {
  59146. return this._blurBoxOffset;
  59147. },
  59148. /**
  59149. * Sets the blur box offset: offset applied during the blur pass.
  59150. * Only usefull if useKernelBlur = false
  59151. */
  59152. set: function (value) {
  59153. if (this._blurBoxOffset === value) {
  59154. return;
  59155. }
  59156. this._blurBoxOffset = value;
  59157. this._disposeBlurPostProcesses();
  59158. },
  59159. enumerable: true,
  59160. configurable: true
  59161. });
  59162. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59163. /**
  59164. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59165. * 2 means half of the size.
  59166. */
  59167. get: function () {
  59168. return this._blurScale;
  59169. },
  59170. /**
  59171. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59172. * 2 means half of the size.
  59173. */
  59174. set: function (value) {
  59175. if (this._blurScale === value) {
  59176. return;
  59177. }
  59178. this._blurScale = value;
  59179. this._disposeBlurPostProcesses();
  59180. },
  59181. enumerable: true,
  59182. configurable: true
  59183. });
  59184. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59185. /**
  59186. * Gets the blur kernel: kernel size of the blur pass.
  59187. * Only usefull if useKernelBlur = true
  59188. */
  59189. get: function () {
  59190. return this._blurKernel;
  59191. },
  59192. /**
  59193. * Sets the blur kernel: kernel size of the blur pass.
  59194. * Only usefull if useKernelBlur = true
  59195. */
  59196. set: function (value) {
  59197. if (this._blurKernel === value) {
  59198. return;
  59199. }
  59200. this._blurKernel = value;
  59201. this._disposeBlurPostProcesses();
  59202. },
  59203. enumerable: true,
  59204. configurable: true
  59205. });
  59206. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59207. /**
  59208. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59209. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59210. */
  59211. get: function () {
  59212. return this._useKernelBlur;
  59213. },
  59214. /**
  59215. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59216. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59217. */
  59218. set: function (value) {
  59219. if (this._useKernelBlur === value) {
  59220. return;
  59221. }
  59222. this._useKernelBlur = value;
  59223. this._disposeBlurPostProcesses();
  59224. },
  59225. enumerable: true,
  59226. configurable: true
  59227. });
  59228. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59229. /**
  59230. * Gets the depth scale used in ESM mode.
  59231. */
  59232. get: function () {
  59233. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59234. },
  59235. /**
  59236. * Sets the depth scale used in ESM mode.
  59237. * This can override the scale stored on the light.
  59238. */
  59239. set: function (value) {
  59240. this._depthScale = value;
  59241. },
  59242. enumerable: true,
  59243. configurable: true
  59244. });
  59245. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59246. /**
  59247. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59248. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59249. */
  59250. get: function () {
  59251. return this._filter;
  59252. },
  59253. /**
  59254. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59255. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59256. */
  59257. set: function (value) {
  59258. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59259. if (this._light.needCube()) {
  59260. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59261. this.useExponentialShadowMap = true;
  59262. return;
  59263. }
  59264. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59265. this.useCloseExponentialShadowMap = true;
  59266. return;
  59267. }
  59268. }
  59269. if (this._filter === value) {
  59270. return;
  59271. }
  59272. this._filter = value;
  59273. this._disposeBlurPostProcesses();
  59274. this._applyFilterValues();
  59275. this._light._markMeshesAsLightDirty();
  59276. },
  59277. enumerable: true,
  59278. configurable: true
  59279. });
  59280. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59281. /**
  59282. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59283. */
  59284. get: function () {
  59285. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59286. },
  59287. /**
  59288. * Sets the current filter to Poisson Sampling aka PCF.
  59289. */
  59290. set: function (value) {
  59291. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59292. return;
  59293. }
  59294. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59300. /**
  59301. * Gets if the current filter is set to VSM.
  59302. * DEPRECATED. Should use useExponentialShadowMap instead.
  59303. */
  59304. get: function () {
  59305. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59306. return this.useExponentialShadowMap;
  59307. },
  59308. /**
  59309. * Sets the current filter is to VSM.
  59310. * DEPRECATED. Should use useExponentialShadowMap instead.
  59311. */
  59312. set: function (value) {
  59313. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59314. this.useExponentialShadowMap = value;
  59315. },
  59316. enumerable: true,
  59317. configurable: true
  59318. });
  59319. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59320. /**
  59321. * Gets if the current filter is set to blurred VSM.
  59322. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59323. */
  59324. get: function () {
  59325. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59326. return this.useBlurExponentialShadowMap;
  59327. },
  59328. /**
  59329. * Sets the current filter is to blurred VSM.
  59330. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59331. */
  59332. set: function (value) {
  59333. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59334. this.useBlurExponentialShadowMap = value;
  59335. },
  59336. enumerable: true,
  59337. configurable: true
  59338. });
  59339. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59340. /**
  59341. * Gets if the current filter is set to ESM.
  59342. */
  59343. get: function () {
  59344. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59345. },
  59346. /**
  59347. * Sets the current filter is to ESM.
  59348. */
  59349. set: function (value) {
  59350. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59351. return;
  59352. }
  59353. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59354. },
  59355. enumerable: true,
  59356. configurable: true
  59357. });
  59358. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59359. /**
  59360. * Gets if the current filter is set to filtered ESM.
  59361. */
  59362. get: function () {
  59363. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59364. },
  59365. /**
  59366. * Gets if the current filter is set to filtered ESM.
  59367. */
  59368. set: function (value) {
  59369. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59370. return;
  59371. }
  59372. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59373. },
  59374. enumerable: true,
  59375. configurable: true
  59376. });
  59377. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59378. /**
  59379. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59380. * exponential to prevent steep falloff artifacts).
  59381. */
  59382. get: function () {
  59383. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59384. },
  59385. /**
  59386. * Sets the current filter to "close ESM" (using the inverse of the
  59387. * exponential to prevent steep falloff artifacts).
  59388. */
  59389. set: function (value) {
  59390. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59391. return;
  59392. }
  59393. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59394. },
  59395. enumerable: true,
  59396. configurable: true
  59397. });
  59398. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59399. /**
  59400. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59401. * exponential to prevent steep falloff artifacts).
  59402. */
  59403. get: function () {
  59404. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59405. },
  59406. /**
  59407. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59408. * exponential to prevent steep falloff artifacts).
  59409. */
  59410. set: function (value) {
  59411. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59412. return;
  59413. }
  59414. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59415. },
  59416. enumerable: true,
  59417. configurable: true
  59418. });
  59419. /**
  59420. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59421. * 0 means strongest and 1 would means no shadow.
  59422. * @returns the darkness.
  59423. */
  59424. ShadowGenerator.prototype.getDarkness = function () {
  59425. return this._darkness;
  59426. };
  59427. /**
  59428. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59429. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59430. * @returns the shadow generator allowing fluent coding.
  59431. */
  59432. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59433. if (darkness >= 1.0)
  59434. this._darkness = 1.0;
  59435. else if (darkness <= 0.0)
  59436. this._darkness = 0.0;
  59437. else
  59438. this._darkness = darkness;
  59439. return this;
  59440. };
  59441. /**
  59442. * Sets the ability to have transparent shadow (boolean).
  59443. * @param transparent True if transparent else False
  59444. * @returns the shadow generator allowing fluent coding
  59445. */
  59446. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59447. this._transparencyShadow = transparent;
  59448. return this;
  59449. };
  59450. /**
  59451. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59452. * @returns The render target texture if present otherwise, null
  59453. */
  59454. ShadowGenerator.prototype.getShadowMap = function () {
  59455. return this._shadowMap;
  59456. };
  59457. /**
  59458. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59459. * @returns The render target texture if the shadow map is present otherwise, null
  59460. */
  59461. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59462. if (this._shadowMap2) {
  59463. return this._shadowMap2;
  59464. }
  59465. return this._shadowMap;
  59466. };
  59467. /**
  59468. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59469. * @param mesh Mesh to add
  59470. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59471. * @returns the Shadow Generator itself
  59472. */
  59473. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59474. if (includeDescendants === void 0) { includeDescendants = true; }
  59475. if (!this._shadowMap) {
  59476. return this;
  59477. }
  59478. if (!this._shadowMap.renderList) {
  59479. this._shadowMap.renderList = [];
  59480. }
  59481. this._shadowMap.renderList.push(mesh);
  59482. if (includeDescendants) {
  59483. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59484. }
  59485. return this;
  59486. var _a;
  59487. };
  59488. /**
  59489. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59490. * @param mesh Mesh to remove
  59491. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59492. * @returns the Shadow Generator itself
  59493. */
  59494. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59495. if (includeDescendants === void 0) { includeDescendants = true; }
  59496. if (!this._shadowMap || !this._shadowMap.renderList) {
  59497. return this;
  59498. }
  59499. var index = this._shadowMap.renderList.indexOf(mesh);
  59500. if (index !== -1) {
  59501. this._shadowMap.renderList.splice(index, 1);
  59502. }
  59503. if (includeDescendants) {
  59504. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59505. var child = _a[_i];
  59506. this.removeShadowCaster(child);
  59507. }
  59508. }
  59509. return this;
  59510. };
  59511. /**
  59512. * Returns the associated light object.
  59513. * @returns the light generating the shadow
  59514. */
  59515. ShadowGenerator.prototype.getLight = function () {
  59516. return this._light;
  59517. };
  59518. ShadowGenerator.prototype._initializeGenerator = function () {
  59519. this._light._markMeshesAsLightDirty();
  59520. this._initializeShadowMap();
  59521. };
  59522. ShadowGenerator.prototype._initializeShadowMap = function () {
  59523. var _this = this;
  59524. // Render target
  59525. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59526. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59527. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59528. this._shadowMap.anisotropicFilteringLevel = 1;
  59529. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59530. this._shadowMap.renderParticles = false;
  59531. this._shadowMap.ignoreCameraViewport = true;
  59532. // Record Face Index before render.
  59533. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59534. _this._currentFaceIndex = faceIndex;
  59535. });
  59536. // Custom render function.
  59537. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59538. // Blur if required afer render.
  59539. this._shadowMap.onAfterUnbindObservable.add(function () {
  59540. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59541. return;
  59542. }
  59543. var shadowMap = _this.getShadowMapForRendering();
  59544. if (shadowMap) {
  59545. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59546. }
  59547. });
  59548. // Clear according to the chosen filter.
  59549. this._shadowMap.onClearObservable.add(function (engine) {
  59550. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59551. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59552. }
  59553. else {
  59554. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59555. }
  59556. });
  59557. };
  59558. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59559. var _this = this;
  59560. var engine = this._scene.getEngine();
  59561. var targetSize = this._mapSize / this.blurScale;
  59562. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59563. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59564. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59565. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59566. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59567. }
  59568. if (this.useKernelBlur) {
  59569. 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);
  59570. this._kernelBlurXPostprocess.width = targetSize;
  59571. this._kernelBlurXPostprocess.height = targetSize;
  59572. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59573. effect.setTexture("textureSampler", _this._shadowMap);
  59574. });
  59575. 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);
  59576. this._kernelBlurXPostprocess.autoClear = false;
  59577. this._kernelBlurYPostprocess.autoClear = false;
  59578. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59579. this._kernelBlurXPostprocess.packedFloat = true;
  59580. this._kernelBlurYPostprocess.packedFloat = true;
  59581. }
  59582. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59583. }
  59584. else {
  59585. 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);
  59586. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59587. effect.setFloat2("screenSize", targetSize, targetSize);
  59588. effect.setTexture("textureSampler", _this._shadowMap);
  59589. });
  59590. this._boxBlurPostprocess.autoClear = false;
  59591. this._blurPostProcesses = [this._boxBlurPostprocess];
  59592. }
  59593. };
  59594. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59595. var index;
  59596. var engine = this._scene.getEngine();
  59597. if (depthOnlySubMeshes.length) {
  59598. engine.setColorWrite(false);
  59599. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59600. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59601. }
  59602. engine.setColorWrite(true);
  59603. }
  59604. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59605. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59606. }
  59607. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59608. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59609. }
  59610. if (this._transparencyShadow) {
  59611. for (index = 0; index < transparentSubMeshes.length; index++) {
  59612. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59613. }
  59614. }
  59615. };
  59616. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59617. var _this = this;
  59618. var mesh = subMesh.getRenderingMesh();
  59619. var scene = this._scene;
  59620. var engine = scene.getEngine();
  59621. var material = subMesh.getMaterial();
  59622. if (!material) {
  59623. return;
  59624. }
  59625. // Culling
  59626. engine.setState(material.backFaceCulling);
  59627. // Managing instances
  59628. var batch = mesh._getInstancesRenderList(subMesh._id);
  59629. if (batch.mustReturn) {
  59630. return;
  59631. }
  59632. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59633. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59634. engine.enableEffect(this._effect);
  59635. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59636. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59637. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59638. this._effect.setVector3("lightPosition", this.getLight().position);
  59639. if (scene.activeCamera) {
  59640. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59641. }
  59642. // Alpha test
  59643. if (material && material.needAlphaTesting()) {
  59644. var alphaTexture = material.getAlphaTestTexture();
  59645. if (alphaTexture) {
  59646. this._effect.setTexture("diffuseSampler", alphaTexture);
  59647. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59648. }
  59649. }
  59650. // Bones
  59651. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59652. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59653. }
  59654. if (this.forceBackFacesOnly) {
  59655. engine.setState(true, 0, false, true);
  59656. }
  59657. // Draw
  59658. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59659. if (this.forceBackFacesOnly) {
  59660. engine.setState(true, 0, false, false);
  59661. }
  59662. }
  59663. else {
  59664. // Need to reset refresh rate of the shadowMap
  59665. if (this._shadowMap) {
  59666. this._shadowMap.resetRefreshCounter();
  59667. }
  59668. }
  59669. };
  59670. ShadowGenerator.prototype._applyFilterValues = function () {
  59671. if (!this._shadowMap) {
  59672. return;
  59673. }
  59674. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59675. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59676. }
  59677. else {
  59678. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59679. }
  59680. };
  59681. /**
  59682. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59683. * @param onCompiled Callback triggered at the and of the effects compilation
  59684. * @param options Sets of optional options forcing the compilation with different modes
  59685. */
  59686. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59687. var _this = this;
  59688. var localOptions = __assign({ useInstances: false }, options);
  59689. var shadowMap = this.getShadowMap();
  59690. if (!shadowMap) {
  59691. if (onCompiled) {
  59692. onCompiled(this);
  59693. }
  59694. return;
  59695. }
  59696. var renderList = shadowMap.renderList;
  59697. if (!renderList) {
  59698. if (onCompiled) {
  59699. onCompiled(this);
  59700. }
  59701. return;
  59702. }
  59703. var subMeshes = new Array();
  59704. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59705. var mesh = renderList_1[_i];
  59706. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59707. }
  59708. if (subMeshes.length === 0) {
  59709. if (onCompiled) {
  59710. onCompiled(this);
  59711. }
  59712. return;
  59713. }
  59714. var currentIndex = 0;
  59715. var checkReady = function () {
  59716. if (!_this._scene || !_this._scene.getEngine()) {
  59717. return;
  59718. }
  59719. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59720. currentIndex++;
  59721. if (currentIndex >= subMeshes.length) {
  59722. if (onCompiled) {
  59723. onCompiled(_this);
  59724. }
  59725. return;
  59726. }
  59727. }
  59728. setTimeout(checkReady, 16);
  59729. };
  59730. checkReady();
  59731. };
  59732. /**
  59733. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59734. * @param options Sets of optional options forcing the compilation with different modes
  59735. * @returns A promise that resolves when the compilation completes
  59736. */
  59737. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59738. var _this = this;
  59739. return new Promise(function (resolve) {
  59740. _this.forceCompilation(function () {
  59741. resolve();
  59742. }, options);
  59743. });
  59744. };
  59745. /**
  59746. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59747. * @param subMesh The submesh we want to render in the shadow map
  59748. * @param useInstances Defines wether will draw in the map using instances
  59749. * @returns true if ready otherwise, false
  59750. */
  59751. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59752. var defines = [];
  59753. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59754. defines.push("#define FLOAT");
  59755. }
  59756. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59757. defines.push("#define ESM");
  59758. }
  59759. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59760. var mesh = subMesh.getMesh();
  59761. var material = subMesh.getMaterial();
  59762. // Alpha test
  59763. if (material && material.needAlphaTesting()) {
  59764. var alphaTexture = material.getAlphaTestTexture();
  59765. if (alphaTexture) {
  59766. defines.push("#define ALPHATEST");
  59767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59768. attribs.push(BABYLON.VertexBuffer.UVKind);
  59769. defines.push("#define UV1");
  59770. }
  59771. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59772. if (alphaTexture.coordinatesIndex === 1) {
  59773. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59774. defines.push("#define UV2");
  59775. }
  59776. }
  59777. }
  59778. }
  59779. // Bones
  59780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59781. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59782. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59783. if (mesh.numBoneInfluencers > 4) {
  59784. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59785. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59786. }
  59787. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59788. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59789. }
  59790. else {
  59791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59792. }
  59793. // Instances
  59794. if (useInstances) {
  59795. defines.push("#define INSTANCES");
  59796. attribs.push("world0");
  59797. attribs.push("world1");
  59798. attribs.push("world2");
  59799. attribs.push("world3");
  59800. }
  59801. // Get correct effect
  59802. var join = defines.join("\n");
  59803. if (this._cachedDefines !== join) {
  59804. this._cachedDefines = join;
  59805. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59806. }
  59807. if (!this._effect.isReady()) {
  59808. return false;
  59809. }
  59810. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59811. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59812. this._initializeBlurRTTAndPostProcesses();
  59813. }
  59814. }
  59815. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59816. return false;
  59817. }
  59818. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59819. return false;
  59820. }
  59821. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59822. return false;
  59823. }
  59824. return true;
  59825. };
  59826. /**
  59827. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59828. * @param defines Defines of the material we want to update
  59829. * @param lightIndex Index of the light in the enabled light list of the material
  59830. */
  59831. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59832. var scene = this._scene;
  59833. var light = this._light;
  59834. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59835. return;
  59836. }
  59837. defines["SHADOW" + lightIndex] = true;
  59838. if (this.usePoissonSampling) {
  59839. defines["SHADOWPCF" + lightIndex] = true;
  59840. }
  59841. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59842. defines["SHADOWESM" + lightIndex] = true;
  59843. }
  59844. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59845. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59846. }
  59847. if (light.needCube()) {
  59848. defines["SHADOWCUBE" + lightIndex] = true;
  59849. }
  59850. };
  59851. /**
  59852. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59853. * defined in the generator but impacting the effect).
  59854. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59855. * @param effect The effect we are binfing the information for
  59856. */
  59857. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59858. var light = this._light;
  59859. var scene = this._scene;
  59860. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59861. return;
  59862. }
  59863. var camera = scene.activeCamera;
  59864. if (!camera) {
  59865. return;
  59866. }
  59867. var shadowMap = this.getShadowMap();
  59868. if (!shadowMap) {
  59869. return;
  59870. }
  59871. if (!light.needCube()) {
  59872. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59873. }
  59874. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59875. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59876. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59877. };
  59878. /**
  59879. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59880. * (eq to shadow prjection matrix * light transform matrix)
  59881. * @returns The transform matrix used to create the shadow map
  59882. */
  59883. ShadowGenerator.prototype.getTransformMatrix = function () {
  59884. var scene = this._scene;
  59885. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59886. return this._transformMatrix;
  59887. }
  59888. this._currentRenderID = scene.getRenderId();
  59889. this._currentFaceIndexCache = this._currentFaceIndex;
  59890. var lightPosition = this._light.position;
  59891. if (this._light.computeTransformedInformation()) {
  59892. lightPosition = this._light.transformedPosition;
  59893. }
  59894. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59895. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59896. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59897. }
  59898. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59899. this._cachedPosition = lightPosition.clone();
  59900. this._cachedDirection = this._lightDirection.clone();
  59901. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59902. var shadowMap = this.getShadowMap();
  59903. if (shadowMap) {
  59904. var renderList = shadowMap.renderList;
  59905. if (renderList) {
  59906. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59907. }
  59908. }
  59909. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59910. }
  59911. return this._transformMatrix;
  59912. };
  59913. /**
  59914. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59915. * Cube and 2D textures for instance.
  59916. */
  59917. ShadowGenerator.prototype.recreateShadowMap = function () {
  59918. var shadowMap = this._shadowMap;
  59919. if (!shadowMap) {
  59920. return;
  59921. }
  59922. // Track render list.
  59923. var renderList = shadowMap.renderList;
  59924. // Clean up existing data.
  59925. this._disposeRTTandPostProcesses();
  59926. // Reinitializes.
  59927. this._initializeGenerator();
  59928. // Reaffect the filter to ensure a correct fallback if necessary.
  59929. this.filter = this.filter;
  59930. // Reaffect the filter.
  59931. this._applyFilterValues();
  59932. // Reaffect Render List.
  59933. this._shadowMap.renderList = renderList;
  59934. };
  59935. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59936. if (this._shadowMap2) {
  59937. this._shadowMap2.dispose();
  59938. this._shadowMap2 = null;
  59939. }
  59940. if (this._boxBlurPostprocess) {
  59941. this._boxBlurPostprocess.dispose();
  59942. this._boxBlurPostprocess = null;
  59943. }
  59944. if (this._kernelBlurXPostprocess) {
  59945. this._kernelBlurXPostprocess.dispose();
  59946. this._kernelBlurXPostprocess = null;
  59947. }
  59948. if (this._kernelBlurYPostprocess) {
  59949. this._kernelBlurYPostprocess.dispose();
  59950. this._kernelBlurYPostprocess = null;
  59951. }
  59952. this._blurPostProcesses = [];
  59953. };
  59954. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59955. if (this._shadowMap) {
  59956. this._shadowMap.dispose();
  59957. this._shadowMap = null;
  59958. }
  59959. this._disposeBlurPostProcesses();
  59960. };
  59961. /**
  59962. * Disposes the ShadowGenerator.
  59963. * Returns nothing.
  59964. */
  59965. ShadowGenerator.prototype.dispose = function () {
  59966. this._disposeRTTandPostProcesses();
  59967. if (this._light) {
  59968. this._light._shadowGenerator = null;
  59969. this._light._markMeshesAsLightDirty();
  59970. }
  59971. };
  59972. /**
  59973. * Serializes the shadow generator setup to a json object.
  59974. * @returns The serialized JSON object
  59975. */
  59976. ShadowGenerator.prototype.serialize = function () {
  59977. var serializationObject = {};
  59978. var shadowMap = this.getShadowMap();
  59979. if (!shadowMap) {
  59980. return serializationObject;
  59981. }
  59982. serializationObject.lightId = this._light.id;
  59983. serializationObject.mapSize = shadowMap.getRenderSize();
  59984. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59985. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59986. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59987. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59988. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59989. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59990. serializationObject.depthScale = this.depthScale;
  59991. serializationObject.darkness = this.getDarkness();
  59992. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59993. serializationObject.blurKernel = this.blurKernel;
  59994. serializationObject.blurScale = this.blurScale;
  59995. serializationObject.useKernelBlur = this.useKernelBlur;
  59996. serializationObject.transparencyShadow = this._transparencyShadow;
  59997. serializationObject.renderList = [];
  59998. if (shadowMap.renderList) {
  59999. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60000. var mesh = shadowMap.renderList[meshIndex];
  60001. serializationObject.renderList.push(mesh.id);
  60002. }
  60003. }
  60004. return serializationObject;
  60005. };
  60006. /**
  60007. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60008. * @param parsedShadowGenerator The JSON object to parse
  60009. * @param scene The scene to create the shadow map for
  60010. * @returns The parsed shadow generator
  60011. */
  60012. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60013. //casting to point light, as light is missing the position attr and typescript complains.
  60014. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60015. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60016. var shadowMap = shadowGenerator.getShadowMap();
  60017. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60018. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60019. meshes.forEach(function (mesh) {
  60020. if (!shadowMap) {
  60021. return;
  60022. }
  60023. if (!shadowMap.renderList) {
  60024. shadowMap.renderList = [];
  60025. }
  60026. shadowMap.renderList.push(mesh);
  60027. });
  60028. }
  60029. if (parsedShadowGenerator.usePoissonSampling) {
  60030. shadowGenerator.usePoissonSampling = true;
  60031. }
  60032. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60033. shadowGenerator.useExponentialShadowMap = true;
  60034. }
  60035. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60036. shadowGenerator.useBlurExponentialShadowMap = true;
  60037. }
  60038. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60039. shadowGenerator.useCloseExponentialShadowMap = true;
  60040. }
  60041. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60042. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60043. }
  60044. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60045. shadowGenerator.useExponentialShadowMap = true;
  60046. }
  60047. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60048. shadowGenerator.useBlurExponentialShadowMap = true;
  60049. }
  60050. if (parsedShadowGenerator.depthScale) {
  60051. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60052. }
  60053. if (parsedShadowGenerator.blurScale) {
  60054. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60055. }
  60056. if (parsedShadowGenerator.blurBoxOffset) {
  60057. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60058. }
  60059. if (parsedShadowGenerator.useKernelBlur) {
  60060. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60061. }
  60062. if (parsedShadowGenerator.blurKernel) {
  60063. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60064. }
  60065. if (parsedShadowGenerator.bias !== undefined) {
  60066. shadowGenerator.bias = parsedShadowGenerator.bias;
  60067. }
  60068. if (parsedShadowGenerator.darkness) {
  60069. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60070. }
  60071. if (parsedShadowGenerator.transparencyShadow) {
  60072. shadowGenerator.setTransparencyShadow(true);
  60073. }
  60074. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60075. return shadowGenerator;
  60076. };
  60077. ShadowGenerator._FILTER_NONE = 0;
  60078. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60079. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60080. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60081. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60082. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60083. return ShadowGenerator;
  60084. }());
  60085. BABYLON.ShadowGenerator = ShadowGenerator;
  60086. })(BABYLON || (BABYLON = {}));
  60087. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60088. var BABYLON;
  60089. (function (BABYLON) {
  60090. var DefaultLoadingScreen = /** @class */ (function () {
  60091. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60092. if (_loadingText === void 0) { _loadingText = ""; }
  60093. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60094. var _this = this;
  60095. this._renderingCanvas = _renderingCanvas;
  60096. this._loadingText = _loadingText;
  60097. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60098. // Resize
  60099. this._resizeLoadingUI = function () {
  60100. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60101. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60102. if (!_this._loadingDiv) {
  60103. return;
  60104. }
  60105. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60106. _this._loadingDiv.style.left = canvasRect.left + "px";
  60107. _this._loadingDiv.style.top = canvasRect.top + "px";
  60108. _this._loadingDiv.style.width = canvasRect.width + "px";
  60109. _this._loadingDiv.style.height = canvasRect.height + "px";
  60110. };
  60111. }
  60112. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60113. if (this._loadingDiv) {
  60114. // Do not add a loading screen if there is already one
  60115. return;
  60116. }
  60117. this._loadingDiv = document.createElement("div");
  60118. this._loadingDiv.id = "babylonjsLoadingDiv";
  60119. this._loadingDiv.style.opacity = "0";
  60120. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60121. this._loadingDiv.style.pointerEvents = "none";
  60122. // Loading text
  60123. this._loadingTextDiv = document.createElement("div");
  60124. this._loadingTextDiv.style.position = "absolute";
  60125. this._loadingTextDiv.style.left = "0";
  60126. this._loadingTextDiv.style.top = "50%";
  60127. this._loadingTextDiv.style.marginTop = "80px";
  60128. this._loadingTextDiv.style.width = "100%";
  60129. this._loadingTextDiv.style.height = "20px";
  60130. this._loadingTextDiv.style.fontFamily = "Arial";
  60131. this._loadingTextDiv.style.fontSize = "14px";
  60132. this._loadingTextDiv.style.color = "white";
  60133. this._loadingTextDiv.style.textAlign = "center";
  60134. this._loadingTextDiv.innerHTML = "Loading";
  60135. this._loadingDiv.appendChild(this._loadingTextDiv);
  60136. //set the predefined text
  60137. this._loadingTextDiv.innerHTML = this._loadingText;
  60138. // Generating keyframes
  60139. var style = document.createElement('style');
  60140. style.type = 'text/css';
  60141. 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 }";
  60142. style.innerHTML = keyFrames;
  60143. document.getElementsByTagName('head')[0].appendChild(style);
  60144. // Loading img
  60145. var imgBack = new Image();
  60146. 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";
  60147. imgBack.style.position = "absolute";
  60148. imgBack.style.left = "50%";
  60149. imgBack.style.top = "50%";
  60150. imgBack.style.marginLeft = "-60px";
  60151. imgBack.style.marginTop = "-60px";
  60152. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60153. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60154. imgBack.style.transformOrigin = "50% 50%";
  60155. imgBack.style.webkitTransformOrigin = "50% 50%";
  60156. this._loadingDiv.appendChild(imgBack);
  60157. this._resizeLoadingUI();
  60158. window.addEventListener("resize", this._resizeLoadingUI);
  60159. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60160. document.body.appendChild(this._loadingDiv);
  60161. this._loadingDiv.style.opacity = "1";
  60162. };
  60163. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60164. var _this = this;
  60165. if (!this._loadingDiv) {
  60166. return;
  60167. }
  60168. var onTransitionEnd = function () {
  60169. if (!_this._loadingDiv) {
  60170. return;
  60171. }
  60172. document.body.removeChild(_this._loadingDiv);
  60173. window.removeEventListener("resize", _this._resizeLoadingUI);
  60174. _this._loadingDiv = null;
  60175. };
  60176. this._loadingDiv.style.opacity = "0";
  60177. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60178. };
  60179. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60180. set: function (text) {
  60181. this._loadingText = text;
  60182. if (this._loadingTextDiv) {
  60183. this._loadingTextDiv.innerHTML = this._loadingText;
  60184. }
  60185. },
  60186. enumerable: true,
  60187. configurable: true
  60188. });
  60189. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60190. get: function () {
  60191. return this._loadingDivBackgroundColor;
  60192. },
  60193. set: function (color) {
  60194. this._loadingDivBackgroundColor = color;
  60195. if (!this._loadingDiv) {
  60196. return;
  60197. }
  60198. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. return DefaultLoadingScreen;
  60204. }());
  60205. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60206. })(BABYLON || (BABYLON = {}));
  60207. //# sourceMappingURL=babylon.loadingScreen.js.map
  60208. var BABYLON;
  60209. (function (BABYLON) {
  60210. var SceneLoaderProgressEvent = /** @class */ (function () {
  60211. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60212. this.lengthComputable = lengthComputable;
  60213. this.loaded = loaded;
  60214. this.total = total;
  60215. }
  60216. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60217. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60218. };
  60219. return SceneLoaderProgressEvent;
  60220. }());
  60221. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60222. var SceneLoader = /** @class */ (function () {
  60223. function SceneLoader() {
  60224. }
  60225. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60226. get: function () {
  60227. return 0;
  60228. },
  60229. enumerable: true,
  60230. configurable: true
  60231. });
  60232. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60233. get: function () {
  60234. return 1;
  60235. },
  60236. enumerable: true,
  60237. configurable: true
  60238. });
  60239. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60240. get: function () {
  60241. return 2;
  60242. },
  60243. enumerable: true,
  60244. configurable: true
  60245. });
  60246. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60247. get: function () {
  60248. return 3;
  60249. },
  60250. enumerable: true,
  60251. configurable: true
  60252. });
  60253. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60254. get: function () {
  60255. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60256. },
  60257. set: function (value) {
  60258. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60259. },
  60260. enumerable: true,
  60261. configurable: true
  60262. });
  60263. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60264. get: function () {
  60265. return SceneLoader._ShowLoadingScreen;
  60266. },
  60267. set: function (value) {
  60268. SceneLoader._ShowLoadingScreen = value;
  60269. },
  60270. enumerable: true,
  60271. configurable: true
  60272. });
  60273. Object.defineProperty(SceneLoader, "loggingLevel", {
  60274. get: function () {
  60275. return SceneLoader._loggingLevel;
  60276. },
  60277. set: function (value) {
  60278. SceneLoader._loggingLevel = value;
  60279. },
  60280. enumerable: true,
  60281. configurable: true
  60282. });
  60283. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60284. get: function () {
  60285. return SceneLoader._CleanBoneMatrixWeights;
  60286. },
  60287. set: function (value) {
  60288. SceneLoader._CleanBoneMatrixWeights = value;
  60289. },
  60290. enumerable: true,
  60291. configurable: true
  60292. });
  60293. SceneLoader._getDefaultPlugin = function () {
  60294. return SceneLoader._registeredPlugins[".babylon"];
  60295. };
  60296. SceneLoader._getPluginForExtension = function (extension) {
  60297. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60298. if (registeredPlugin) {
  60299. return registeredPlugin;
  60300. }
  60301. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60302. return SceneLoader._getDefaultPlugin();
  60303. };
  60304. SceneLoader._getPluginForDirectLoad = function (data) {
  60305. for (var extension in SceneLoader._registeredPlugins) {
  60306. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60307. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60308. return SceneLoader._registeredPlugins[extension];
  60309. }
  60310. }
  60311. return SceneLoader._getDefaultPlugin();
  60312. };
  60313. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60314. if (sceneFilename.name) {
  60315. sceneFilename = sceneFilename.name;
  60316. }
  60317. var queryStringPosition = sceneFilename.indexOf("?");
  60318. if (queryStringPosition !== -1) {
  60319. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60320. }
  60321. var dotPosition = sceneFilename.lastIndexOf(".");
  60322. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60323. return SceneLoader._getPluginForExtension(extension);
  60324. };
  60325. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60326. SceneLoader._getDirectLoad = function (sceneFilename) {
  60327. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60328. return sceneFilename.substr(5);
  60329. }
  60330. return null;
  60331. };
  60332. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60333. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60334. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60335. var plugin;
  60336. if (registeredPlugin.plugin.createPlugin) {
  60337. plugin = registeredPlugin.plugin.createPlugin();
  60338. }
  60339. else {
  60340. plugin = registeredPlugin.plugin;
  60341. }
  60342. var useArrayBuffer = registeredPlugin.isBinary;
  60343. var database;
  60344. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60345. var dataCallback = function (data, responseURL) {
  60346. if (scene.isDisposed) {
  60347. onError("Scene has been disposed");
  60348. return;
  60349. }
  60350. scene.database = database;
  60351. onSuccess(plugin, data, responseURL);
  60352. };
  60353. var request = null;
  60354. var pluginDisposed = false;
  60355. var onDisposeObservable = plugin.onDisposeObservable;
  60356. if (onDisposeObservable) {
  60357. onDisposeObservable.add(function () {
  60358. pluginDisposed = true;
  60359. if (request) {
  60360. request.abort();
  60361. request = null;
  60362. }
  60363. onDispose();
  60364. });
  60365. }
  60366. var manifestChecked = function () {
  60367. if (pluginDisposed) {
  60368. return;
  60369. }
  60370. var url = rootUrl + sceneFilename;
  60371. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60372. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60373. } : undefined, database, useArrayBuffer, function (request, exception) {
  60374. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60375. });
  60376. };
  60377. if (directLoad) {
  60378. dataCallback(directLoad);
  60379. return plugin;
  60380. }
  60381. if (rootUrl.indexOf("file:") === -1) {
  60382. if (scene.getEngine().enableOfflineSupport) {
  60383. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60384. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60385. }
  60386. else {
  60387. manifestChecked();
  60388. }
  60389. }
  60390. else {
  60391. var fileOrString = sceneFilename;
  60392. if (fileOrString.name) {
  60393. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60394. }
  60395. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60396. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60397. }
  60398. else {
  60399. onError("Unable to find file named " + sceneFilename);
  60400. }
  60401. }
  60402. return plugin;
  60403. };
  60404. // Public functions
  60405. SceneLoader.GetPluginForExtension = function (extension) {
  60406. return SceneLoader._getPluginForExtension(extension).plugin;
  60407. };
  60408. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60409. return !!SceneLoader._registeredPlugins[extension];
  60410. };
  60411. SceneLoader.RegisterPlugin = function (plugin) {
  60412. if (typeof plugin.extensions === "string") {
  60413. var extension = plugin.extensions;
  60414. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60415. plugin: plugin,
  60416. isBinary: false
  60417. };
  60418. }
  60419. else {
  60420. var extensions = plugin.extensions;
  60421. Object.keys(extensions).forEach(function (extension) {
  60422. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60423. plugin: plugin,
  60424. isBinary: extensions[extension].isBinary
  60425. };
  60426. });
  60427. }
  60428. };
  60429. /**
  60430. * Import meshes into a scene
  60431. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60432. * @param rootUrl a string that defines the root url for scene and resources
  60433. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60434. * @param scene the instance of BABYLON.Scene to append to
  60435. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60436. * @param onProgress a callback with a progress event for each file being loaded
  60437. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60438. * @param pluginExtension the extension used to determine the plugin
  60439. * @returns The loaded plugin
  60440. */
  60441. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60442. if (onSuccess === void 0) { onSuccess = null; }
  60443. if (onProgress === void 0) { onProgress = null; }
  60444. if (onError === void 0) { onError = null; }
  60445. if (pluginExtension === void 0) { pluginExtension = null; }
  60446. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60447. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60448. return null;
  60449. }
  60450. var loadingToken = {};
  60451. scene._addPendingData(loadingToken);
  60452. var disposeHandler = function () {
  60453. scene._removePendingData(loadingToken);
  60454. };
  60455. var errorHandler = function (message, exception) {
  60456. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60457. if (onError) {
  60458. onError(scene, errorMessage, exception);
  60459. }
  60460. else {
  60461. BABYLON.Tools.Error(errorMessage);
  60462. // should the exception be thrown?
  60463. }
  60464. disposeHandler();
  60465. };
  60466. var progressHandler = onProgress ? function (event) {
  60467. try {
  60468. onProgress(event);
  60469. }
  60470. catch (e) {
  60471. errorHandler("Error in onProgress callback", e);
  60472. }
  60473. } : undefined;
  60474. var successHandler = function (meshes, particleSystems, skeletons) {
  60475. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60476. if (onSuccess) {
  60477. try {
  60478. onSuccess(meshes, particleSystems, skeletons);
  60479. }
  60480. catch (e) {
  60481. errorHandler("Error in onSuccess callback", e);
  60482. }
  60483. }
  60484. scene._removePendingData(loadingToken);
  60485. };
  60486. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60487. if (plugin.rewriteRootURL) {
  60488. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60489. }
  60490. if (sceneFilename === "") {
  60491. if (sceneFilename === "") {
  60492. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60493. }
  60494. }
  60495. if (plugin.importMesh) {
  60496. var syncedPlugin = plugin;
  60497. var meshes = new Array();
  60498. var particleSystems = new Array();
  60499. var skeletons = new Array();
  60500. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60501. return;
  60502. }
  60503. scene.loadingPluginName = plugin.name;
  60504. successHandler(meshes, particleSystems, skeletons);
  60505. }
  60506. else {
  60507. var asyncedPlugin = plugin;
  60508. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60509. scene.loadingPluginName = plugin.name;
  60510. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60511. }).catch(function (error) {
  60512. errorHandler(error.message, error);
  60513. });
  60514. }
  60515. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60516. };
  60517. /**
  60518. * Import meshes into a scene
  60519. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60520. * @param rootUrl a string that defines the root url for scene and resources
  60521. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60522. * @param scene the instance of BABYLON.Scene to append to
  60523. * @param onProgress a callback with a progress event for each file being loaded
  60524. * @param pluginExtension the extension used to determine the plugin
  60525. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60526. */
  60527. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60528. if (onProgress === void 0) { onProgress = null; }
  60529. if (pluginExtension === void 0) { pluginExtension = null; }
  60530. return new Promise(function (resolve, reject) {
  60531. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60532. resolve({
  60533. meshes: meshes,
  60534. particleSystems: particleSystems,
  60535. skeletons: skeletons
  60536. });
  60537. }, onProgress, function (scene, message, exception) {
  60538. reject(exception || new Error(message));
  60539. });
  60540. });
  60541. };
  60542. /**
  60543. * Load a scene
  60544. * @param rootUrl a string that defines the root url for scene and resources
  60545. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60546. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60547. * @param onSuccess a callback with the scene when import succeeds
  60548. * @param onProgress a callback with a progress event for each file being loaded
  60549. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60550. * @param pluginExtension the extension used to determine the plugin
  60551. * @returns The loaded plugin
  60552. */
  60553. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60554. if (onSuccess === void 0) { onSuccess = null; }
  60555. if (onProgress === void 0) { onProgress = null; }
  60556. if (onError === void 0) { onError = null; }
  60557. if (pluginExtension === void 0) { pluginExtension = null; }
  60558. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60559. };
  60560. /**
  60561. * Load a scene
  60562. * @param rootUrl a string that defines the root url for scene and resources
  60563. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60564. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60565. * @param onProgress a callback with a progress event for each file being loaded
  60566. * @param pluginExtension the extension used to determine the plugin
  60567. * @returns The loaded scene
  60568. */
  60569. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60570. if (onProgress === void 0) { onProgress = null; }
  60571. if (pluginExtension === void 0) { pluginExtension = null; }
  60572. return new Promise(function (resolve, reject) {
  60573. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60574. resolve(scene);
  60575. }, onProgress, function (scene, message, exception) {
  60576. reject(exception || new Error(message));
  60577. }, pluginExtension);
  60578. });
  60579. };
  60580. /**
  60581. * Append a scene
  60582. * @param rootUrl a string that defines the root url for scene and resources
  60583. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60584. * @param scene is the instance of BABYLON.Scene to append to
  60585. * @param onSuccess a callback with the scene when import succeeds
  60586. * @param onProgress a callback with a progress event for each file being loaded
  60587. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60588. * @param pluginExtension the extension used to determine the plugin
  60589. * @returns The loaded plugin
  60590. */
  60591. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60592. if (onSuccess === void 0) { onSuccess = null; }
  60593. if (onProgress === void 0) { onProgress = null; }
  60594. if (onError === void 0) { onError = null; }
  60595. if (pluginExtension === void 0) { pluginExtension = null; }
  60596. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60597. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60598. return null;
  60599. }
  60600. if (SceneLoader.ShowLoadingScreen) {
  60601. scene.getEngine().displayLoadingUI();
  60602. }
  60603. var loadingToken = {};
  60604. scene._addPendingData(loadingToken);
  60605. var disposeHandler = function () {
  60606. scene._removePendingData(loadingToken);
  60607. scene.getEngine().hideLoadingUI();
  60608. };
  60609. var errorHandler = function (message, exception) {
  60610. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60611. if (onError) {
  60612. onError(scene, errorMessage, exception);
  60613. }
  60614. else {
  60615. BABYLON.Tools.Error(errorMessage);
  60616. // should the exception be thrown?
  60617. }
  60618. disposeHandler();
  60619. };
  60620. var progressHandler = onProgress ? function (event) {
  60621. try {
  60622. onProgress(event);
  60623. }
  60624. catch (e) {
  60625. errorHandler("Error in onProgress callback", e);
  60626. }
  60627. } : undefined;
  60628. var successHandler = function () {
  60629. if (onSuccess) {
  60630. try {
  60631. onSuccess(scene);
  60632. }
  60633. catch (e) {
  60634. errorHandler("Error in onSuccess callback", e);
  60635. }
  60636. }
  60637. scene._removePendingData(loadingToken);
  60638. };
  60639. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60640. if (sceneFilename === "") {
  60641. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60642. }
  60643. if (plugin.load) {
  60644. var syncedPlugin = plugin;
  60645. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60646. return;
  60647. }
  60648. scene.loadingPluginName = plugin.name;
  60649. successHandler();
  60650. }
  60651. else {
  60652. var asyncedPlugin = plugin;
  60653. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60654. scene.loadingPluginName = plugin.name;
  60655. successHandler();
  60656. }).catch(function (error) {
  60657. errorHandler(error.message, error);
  60658. });
  60659. }
  60660. if (SceneLoader.ShowLoadingScreen) {
  60661. scene.executeWhenReady(function () {
  60662. scene.getEngine().hideLoadingUI();
  60663. });
  60664. }
  60665. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60666. };
  60667. /**
  60668. * Append a scene
  60669. * @param rootUrl a string that defines the root url for scene and resources
  60670. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60671. * @param scene is the instance of BABYLON.Scene to append to
  60672. * @param onProgress a callback with a progress event for each file being loaded
  60673. * @param pluginExtension the extension used to determine the plugin
  60674. * @returns The given scene
  60675. */
  60676. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60677. if (onProgress === void 0) { onProgress = null; }
  60678. if (pluginExtension === void 0) { pluginExtension = null; }
  60679. return new Promise(function (resolve, reject) {
  60680. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60681. resolve(scene);
  60682. }, onProgress, function (scene, message, exception) {
  60683. reject(exception || new Error(message));
  60684. }, pluginExtension);
  60685. });
  60686. };
  60687. /**
  60688. * Load a scene into an asset container
  60689. * @param rootUrl a string that defines the root url for scene and resources
  60690. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60691. * @param scene is the instance of BABYLON.Scene to append to
  60692. * @param onSuccess a callback with the scene when import succeeds
  60693. * @param onProgress a callback with a progress event for each file being loaded
  60694. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60695. * @param pluginExtension the extension used to determine the plugin
  60696. * @returns The loaded plugin
  60697. */
  60698. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60699. if (onSuccess === void 0) { onSuccess = null; }
  60700. if (onProgress === void 0) { onProgress = null; }
  60701. if (onError === void 0) { onError = null; }
  60702. if (pluginExtension === void 0) { pluginExtension = null; }
  60703. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60704. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60705. return null;
  60706. }
  60707. var loadingToken = {};
  60708. scene._addPendingData(loadingToken);
  60709. var disposeHandler = function () {
  60710. scene._removePendingData(loadingToken);
  60711. };
  60712. var errorHandler = function (message, exception) {
  60713. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60714. if (onError) {
  60715. onError(scene, errorMessage, exception);
  60716. }
  60717. else {
  60718. BABYLON.Tools.Error(errorMessage);
  60719. // should the exception be thrown?
  60720. }
  60721. disposeHandler();
  60722. };
  60723. var progressHandler = onProgress ? function (event) {
  60724. try {
  60725. onProgress(event);
  60726. }
  60727. catch (e) {
  60728. errorHandler("Error in onProgress callback", e);
  60729. }
  60730. } : undefined;
  60731. var successHandler = function (assets) {
  60732. if (onSuccess) {
  60733. try {
  60734. onSuccess(assets);
  60735. }
  60736. catch (e) {
  60737. errorHandler("Error in onSuccess callback", e);
  60738. }
  60739. }
  60740. scene._removePendingData(loadingToken);
  60741. };
  60742. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60743. if (plugin.loadAssetContainer) {
  60744. var syncedPlugin = plugin;
  60745. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60746. if (!assetContainer) {
  60747. return;
  60748. }
  60749. scene.loadingPluginName = plugin.name;
  60750. successHandler(assetContainer);
  60751. }
  60752. else if (plugin.loadAssetContainerAsync) {
  60753. var asyncedPlugin = plugin;
  60754. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60755. scene.loadingPluginName = plugin.name;
  60756. successHandler(assetContainer);
  60757. }).catch(function (error) {
  60758. errorHandler(error.message, error);
  60759. });
  60760. }
  60761. else {
  60762. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60763. }
  60764. if (SceneLoader.ShowLoadingScreen) {
  60765. scene.executeWhenReady(function () {
  60766. scene.getEngine().hideLoadingUI();
  60767. });
  60768. }
  60769. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60770. };
  60771. /**
  60772. * Load a scene into an asset container
  60773. * @param rootUrl a string that defines the root url for scene and resources
  60774. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60775. * @param scene is the instance of BABYLON.Scene to append to
  60776. * @param onProgress a callback with a progress event for each file being loaded
  60777. * @param pluginExtension the extension used to determine the plugin
  60778. * @returns The loaded asset container
  60779. */
  60780. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60781. if (onProgress === void 0) { onProgress = null; }
  60782. if (pluginExtension === void 0) { pluginExtension = null; }
  60783. return new Promise(function (resolve, reject) {
  60784. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60785. resolve(assetContainer);
  60786. }, onProgress, function (scene, message, exception) {
  60787. reject(exception || new Error(message));
  60788. }, pluginExtension);
  60789. });
  60790. };
  60791. // Flags
  60792. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60793. SceneLoader._ShowLoadingScreen = true;
  60794. SceneLoader._CleanBoneMatrixWeights = false;
  60795. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60796. // Members
  60797. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60798. SceneLoader._registeredPlugins = {};
  60799. return SceneLoader;
  60800. }());
  60801. BABYLON.SceneLoader = SceneLoader;
  60802. ;
  60803. })(BABYLON || (BABYLON = {}));
  60804. //# sourceMappingURL=babylon.sceneLoader.js.map
  60805. var BABYLON;
  60806. (function (BABYLON) {
  60807. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60808. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60809. var parsedMaterial = parsedData.materials[index];
  60810. if (parsedMaterial.id === id) {
  60811. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60812. }
  60813. }
  60814. return null;
  60815. };
  60816. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60817. for (var i in names) {
  60818. if (mesh.name === names[i]) {
  60819. hierarchyIds.push(mesh.id);
  60820. return true;
  60821. }
  60822. }
  60823. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60824. hierarchyIds.push(mesh.id);
  60825. return true;
  60826. }
  60827. return false;
  60828. };
  60829. var logOperation = function (operation, producer) {
  60830. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60831. };
  60832. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60833. if (addToScene === void 0) { addToScene = false; }
  60834. var container = new BABYLON.AssetContainer(scene);
  60835. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60836. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60837. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60838. // and avoid problems with multiple concurrent .babylon loads.
  60839. var log = "importScene has failed JSON parse";
  60840. try {
  60841. var parsedData = JSON.parse(data);
  60842. log = "";
  60843. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60844. var index;
  60845. var cache;
  60846. // Lights
  60847. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60848. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60849. var parsedLight = parsedData.lights[index];
  60850. var light = BABYLON.Light.Parse(parsedLight, scene);
  60851. if (light) {
  60852. container.lights.push(light);
  60853. log += (index === 0 ? "\n\tLights:" : "");
  60854. log += "\n\t\t" + light.toString(fullDetails);
  60855. }
  60856. }
  60857. }
  60858. // Animations
  60859. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60860. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60861. var parsedAnimation = parsedData.animations[index];
  60862. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60863. scene.animations.push(animation);
  60864. container.animations.push(animation);
  60865. log += (index === 0 ? "\n\tAnimations:" : "");
  60866. log += "\n\t\t" + animation.toString(fullDetails);
  60867. }
  60868. }
  60869. // Materials
  60870. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60871. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60872. var parsedMaterial = parsedData.materials[index];
  60873. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60874. container.materials.push(mat);
  60875. log += (index === 0 ? "\n\tMaterials:" : "");
  60876. log += "\n\t\t" + mat.toString(fullDetails);
  60877. }
  60878. }
  60879. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60880. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60881. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60882. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60883. container.multiMaterials.push(mmat);
  60884. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60885. log += "\n\t\t" + mmat.toString(fullDetails);
  60886. }
  60887. }
  60888. // Morph targets
  60889. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60890. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60891. var managerData = _a[_i];
  60892. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60893. }
  60894. }
  60895. // Skeletons
  60896. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60897. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60898. var parsedSkeleton = parsedData.skeletons[index];
  60899. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60900. container.skeletons.push(skeleton);
  60901. log += (index === 0 ? "\n\tSkeletons:" : "");
  60902. log += "\n\t\t" + skeleton.toString(fullDetails);
  60903. }
  60904. }
  60905. // Geometries
  60906. var geometries = parsedData.geometries;
  60907. if (geometries !== undefined && geometries !== null) {
  60908. var addedGeometry = new Array();
  60909. // Boxes
  60910. var boxes = geometries.boxes;
  60911. if (boxes !== undefined && boxes !== null) {
  60912. for (index = 0, cache = boxes.length; index < cache; index++) {
  60913. var parsedBox = boxes[index];
  60914. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60915. }
  60916. }
  60917. // Spheres
  60918. var spheres = geometries.spheres;
  60919. if (spheres !== undefined && spheres !== null) {
  60920. for (index = 0, cache = spheres.length; index < cache; index++) {
  60921. var parsedSphere = spheres[index];
  60922. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60923. }
  60924. }
  60925. // Cylinders
  60926. var cylinders = geometries.cylinders;
  60927. if (cylinders !== undefined && cylinders !== null) {
  60928. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60929. var parsedCylinder = cylinders[index];
  60930. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60931. }
  60932. }
  60933. // Toruses
  60934. var toruses = geometries.toruses;
  60935. if (toruses !== undefined && toruses !== null) {
  60936. for (index = 0, cache = toruses.length; index < cache; index++) {
  60937. var parsedTorus = toruses[index];
  60938. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60939. }
  60940. }
  60941. // Grounds
  60942. var grounds = geometries.grounds;
  60943. if (grounds !== undefined && grounds !== null) {
  60944. for (index = 0, cache = grounds.length; index < cache; index++) {
  60945. var parsedGround = grounds[index];
  60946. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60947. }
  60948. }
  60949. // Planes
  60950. var planes = geometries.planes;
  60951. if (planes !== undefined && planes !== null) {
  60952. for (index = 0, cache = planes.length; index < cache; index++) {
  60953. var parsedPlane = planes[index];
  60954. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60955. }
  60956. }
  60957. // TorusKnots
  60958. var torusKnots = geometries.torusKnots;
  60959. if (torusKnots !== undefined && torusKnots !== null) {
  60960. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60961. var parsedTorusKnot = torusKnots[index];
  60962. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60963. }
  60964. }
  60965. // VertexData
  60966. var vertexData = geometries.vertexData;
  60967. if (vertexData !== undefined && vertexData !== null) {
  60968. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60969. var parsedVertexData = vertexData[index];
  60970. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60971. }
  60972. }
  60973. addedGeometry.forEach(function (g) {
  60974. if (g) {
  60975. container.geometries.push(g);
  60976. }
  60977. });
  60978. }
  60979. // Transform nodes
  60980. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60981. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60982. var parsedTransformNode = parsedData.transformNodes[index];
  60983. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60984. container.transformNodes.push(node);
  60985. }
  60986. }
  60987. // Meshes
  60988. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60989. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60990. var parsedMesh = parsedData.meshes[index];
  60991. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60992. container.meshes.push(mesh);
  60993. log += (index === 0 ? "\n\tMeshes:" : "");
  60994. log += "\n\t\t" + mesh.toString(fullDetails);
  60995. }
  60996. }
  60997. // Cameras
  60998. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60999. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61000. var parsedCamera = parsedData.cameras[index];
  61001. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61002. container.cameras.push(camera);
  61003. log += (index === 0 ? "\n\tCameras:" : "");
  61004. log += "\n\t\t" + camera.toString(fullDetails);
  61005. }
  61006. }
  61007. // Browsing all the graph to connect the dots
  61008. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61009. var camera = scene.cameras[index];
  61010. if (camera._waitingParentId) {
  61011. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61012. camera._waitingParentId = null;
  61013. }
  61014. }
  61015. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61016. var light_1 = scene.lights[index];
  61017. if (light_1 && light_1._waitingParentId) {
  61018. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61019. light_1._waitingParentId = null;
  61020. }
  61021. }
  61022. // Sounds
  61023. // TODO: add sound
  61024. var loadedSounds = [];
  61025. var loadedSound;
  61026. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61027. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61028. var parsedSound = parsedData.sounds[index];
  61029. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61030. if (!parsedSound.url)
  61031. parsedSound.url = parsedSound.name;
  61032. if (!loadedSounds[parsedSound.url]) {
  61033. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61034. loadedSounds[parsedSound.url] = loadedSound;
  61035. container.sounds.push(loadedSound);
  61036. }
  61037. else {
  61038. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61039. }
  61040. }
  61041. else {
  61042. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61043. }
  61044. }
  61045. }
  61046. loadedSounds = [];
  61047. // Connect parents & children and parse actions
  61048. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61049. var transformNode = scene.transformNodes[index];
  61050. if (transformNode._waitingParentId) {
  61051. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61052. transformNode._waitingParentId = null;
  61053. }
  61054. }
  61055. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61056. var mesh = scene.meshes[index];
  61057. if (mesh._waitingParentId) {
  61058. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61059. mesh._waitingParentId = null;
  61060. }
  61061. if (mesh._waitingActions) {
  61062. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61063. mesh._waitingActions = null;
  61064. }
  61065. }
  61066. // freeze world matrix application
  61067. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61068. var currentMesh = scene.meshes[index];
  61069. if (currentMesh._waitingFreezeWorldMatrix) {
  61070. currentMesh.freezeWorldMatrix();
  61071. currentMesh._waitingFreezeWorldMatrix = null;
  61072. }
  61073. else {
  61074. currentMesh.computeWorldMatrix(true);
  61075. }
  61076. }
  61077. // Particles Systems
  61078. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61079. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61080. var parsedParticleSystem = parsedData.particleSystems[index];
  61081. if (parsedParticleSystem.activeParticleCount) {
  61082. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61083. container.particleSystems.push(ps);
  61084. }
  61085. else {
  61086. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61087. container.particleSystems.push(ps);
  61088. }
  61089. }
  61090. }
  61091. // Lens flares
  61092. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61093. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61094. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61095. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61096. container.lensFlareSystems.push(lf);
  61097. }
  61098. }
  61099. // Shadows
  61100. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61101. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61102. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61103. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61104. container.shadowGenerators.push(sg);
  61105. }
  61106. }
  61107. // Lights exclusions / inclusions
  61108. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61109. var light_2 = scene.lights[index];
  61110. // Excluded check
  61111. if (light_2._excludedMeshesIds.length > 0) {
  61112. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61113. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61114. if (excludedMesh) {
  61115. light_2.excludedMeshes.push(excludedMesh);
  61116. }
  61117. }
  61118. light_2._excludedMeshesIds = [];
  61119. }
  61120. // Included check
  61121. if (light_2._includedOnlyMeshesIds.length > 0) {
  61122. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61123. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61124. if (includedOnlyMesh) {
  61125. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61126. }
  61127. }
  61128. light_2._includedOnlyMeshesIds = [];
  61129. }
  61130. }
  61131. // Actions (scene)
  61132. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61133. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61134. }
  61135. if (!addToScene) {
  61136. container.removeAllFromScene();
  61137. }
  61138. }
  61139. catch (err) {
  61140. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61141. if (onError) {
  61142. onError(msg, err);
  61143. }
  61144. else {
  61145. BABYLON.Tools.Log(msg);
  61146. throw err;
  61147. }
  61148. }
  61149. finally {
  61150. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61151. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61152. }
  61153. }
  61154. return container;
  61155. };
  61156. BABYLON.SceneLoader.RegisterPlugin({
  61157. name: "babylon.js",
  61158. extensions: ".babylon",
  61159. canDirectLoad: function (data) {
  61160. if (data.indexOf("babylon") !== -1) {
  61161. return true;
  61162. }
  61163. return false;
  61164. },
  61165. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61166. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61167. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61168. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61169. // and avoid problems with multiple concurrent .babylon loads.
  61170. var log = "importMesh has failed JSON parse";
  61171. try {
  61172. var parsedData = JSON.parse(data);
  61173. log = "";
  61174. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61175. if (!meshesNames) {
  61176. meshesNames = null;
  61177. }
  61178. else if (!Array.isArray(meshesNames)) {
  61179. meshesNames = [meshesNames];
  61180. }
  61181. var hierarchyIds = new Array();
  61182. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61183. var loadedSkeletonsIds = [];
  61184. var loadedMaterialsIds = [];
  61185. var index;
  61186. var cache;
  61187. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61188. var parsedMesh = parsedData.meshes[index];
  61189. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61190. if (meshesNames !== null) {
  61191. // Remove found mesh name from list.
  61192. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61193. }
  61194. //Geometry?
  61195. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61196. //does the file contain geometries?
  61197. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61198. //find the correct geometry and add it to the scene
  61199. var found = false;
  61200. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61201. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61202. return;
  61203. }
  61204. else {
  61205. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61206. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61207. switch (geometryType) {
  61208. case "boxes":
  61209. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61210. break;
  61211. case "spheres":
  61212. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61213. break;
  61214. case "cylinders":
  61215. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61216. break;
  61217. case "toruses":
  61218. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61219. break;
  61220. case "grounds":
  61221. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61222. break;
  61223. case "planes":
  61224. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61225. break;
  61226. case "torusKnots":
  61227. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61228. break;
  61229. case "vertexData":
  61230. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61231. break;
  61232. }
  61233. found = true;
  61234. }
  61235. });
  61236. }
  61237. });
  61238. if (found === false) {
  61239. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61240. }
  61241. }
  61242. }
  61243. // Material ?
  61244. if (parsedMesh.materialId) {
  61245. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61246. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61247. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61248. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61249. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61250. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61251. var subMatId = parsedMultiMaterial.materials[matIndex];
  61252. loadedMaterialsIds.push(subMatId);
  61253. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61254. if (mat) {
  61255. log += "\n\tMaterial " + mat.toString(fullDetails);
  61256. }
  61257. }
  61258. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61259. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61260. if (mmat) {
  61261. materialFound = true;
  61262. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61263. }
  61264. break;
  61265. }
  61266. }
  61267. }
  61268. if (materialFound === false) {
  61269. loadedMaterialsIds.push(parsedMesh.materialId);
  61270. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61271. if (!mat) {
  61272. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61273. }
  61274. else {
  61275. log += "\n\tMaterial " + mat.toString(fullDetails);
  61276. }
  61277. }
  61278. }
  61279. // Skeleton ?
  61280. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61281. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61282. if (skeletonAlreadyLoaded === false) {
  61283. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61284. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61285. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61286. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61287. skeletons.push(skeleton);
  61288. loadedSkeletonsIds.push(parsedSkeleton.id);
  61289. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61290. }
  61291. }
  61292. }
  61293. }
  61294. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61295. meshes.push(mesh);
  61296. log += "\n\tMesh " + mesh.toString(fullDetails);
  61297. }
  61298. }
  61299. // Connecting parents
  61300. var currentMesh;
  61301. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61302. currentMesh = scene.meshes[index];
  61303. if (currentMesh._waitingParentId) {
  61304. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61305. currentMesh._waitingParentId = null;
  61306. }
  61307. }
  61308. // freeze and compute world matrix application
  61309. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61310. currentMesh = scene.meshes[index];
  61311. if (currentMesh._waitingFreezeWorldMatrix) {
  61312. currentMesh.freezeWorldMatrix();
  61313. currentMesh._waitingFreezeWorldMatrix = null;
  61314. }
  61315. else {
  61316. currentMesh.computeWorldMatrix(true);
  61317. }
  61318. }
  61319. }
  61320. // Particles
  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 (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61325. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61326. }
  61327. }
  61328. }
  61329. return true;
  61330. }
  61331. catch (err) {
  61332. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61333. if (onError) {
  61334. onError(msg, err);
  61335. }
  61336. else {
  61337. BABYLON.Tools.Log(msg);
  61338. throw err;
  61339. }
  61340. }
  61341. finally {
  61342. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61343. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61344. }
  61345. }
  61346. return false;
  61347. },
  61348. load: function (scene, data, rootUrl, onError) {
  61349. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61350. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61351. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61352. // and avoid problems with multiple concurrent .babylon loads.
  61353. var log = "importScene has failed JSON parse";
  61354. try {
  61355. var parsedData = JSON.parse(data);
  61356. log = "";
  61357. // Scene
  61358. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61359. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61360. }
  61361. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61362. scene.autoClear = parsedData.autoClear;
  61363. }
  61364. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61365. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61366. }
  61367. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61368. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61369. }
  61370. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61371. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61372. }
  61373. // Fog
  61374. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61375. scene.fogMode = parsedData.fogMode;
  61376. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61377. scene.fogStart = parsedData.fogStart;
  61378. scene.fogEnd = parsedData.fogEnd;
  61379. scene.fogDensity = parsedData.fogDensity;
  61380. log += "\tFog mode for scene: ";
  61381. switch (scene.fogMode) {
  61382. // getters not compiling, so using hardcoded
  61383. case 1:
  61384. log += "exp\n";
  61385. break;
  61386. case 2:
  61387. log += "exp2\n";
  61388. break;
  61389. case 3:
  61390. log += "linear\n";
  61391. break;
  61392. }
  61393. }
  61394. //Physics
  61395. if (parsedData.physicsEnabled) {
  61396. var physicsPlugin;
  61397. if (parsedData.physicsEngine === "cannon") {
  61398. physicsPlugin = new BABYLON.CannonJSPlugin();
  61399. }
  61400. else if (parsedData.physicsEngine === "oimo") {
  61401. physicsPlugin = new BABYLON.OimoJSPlugin();
  61402. }
  61403. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61404. //else - default engine, which is currently oimo
  61405. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61406. scene.enablePhysics(physicsGravity, physicsPlugin);
  61407. }
  61408. // Metadata
  61409. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61410. scene.metadata = parsedData.metadata;
  61411. }
  61412. //collisions, if defined. otherwise, default is true
  61413. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61414. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61415. }
  61416. scene.workerCollisions = !!parsedData.workerCollisions;
  61417. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61418. if (!container) {
  61419. return false;
  61420. }
  61421. if (parsedData.autoAnimate) {
  61422. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61423. }
  61424. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61425. scene.setActiveCameraByID(parsedData.activeCameraID);
  61426. }
  61427. // Environment texture
  61428. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61429. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61430. if (parsedData.createDefaultSkybox === true) {
  61431. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61432. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61433. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61434. }
  61435. }
  61436. // Finish
  61437. return true;
  61438. }
  61439. catch (err) {
  61440. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61441. if (onError) {
  61442. onError(msg, err);
  61443. }
  61444. else {
  61445. BABYLON.Tools.Log(msg);
  61446. throw err;
  61447. }
  61448. }
  61449. finally {
  61450. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61451. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61452. }
  61453. }
  61454. return false;
  61455. },
  61456. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61457. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61458. return container;
  61459. }
  61460. });
  61461. })(BABYLON || (BABYLON = {}));
  61462. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61463. var BABYLON;
  61464. (function (BABYLON) {
  61465. var FilesInput = /** @class */ (function () {
  61466. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61467. this.onProcessFileCallback = function () { return true; };
  61468. this._engine = engine;
  61469. this._currentScene = scene;
  61470. this._sceneLoadedCallback = sceneLoadedCallback;
  61471. this._progressCallback = progressCallback;
  61472. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61473. this._textureLoadingCallback = textureLoadingCallback;
  61474. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61475. this._onReloadCallback = onReloadCallback;
  61476. this._errorCallback = errorCallback;
  61477. }
  61478. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61479. var _this = this;
  61480. if (elementToMonitor) {
  61481. this._elementToMonitor = elementToMonitor;
  61482. this._dragEnterHandler = function (e) { _this.drag(e); };
  61483. this._dragOverHandler = function (e) { _this.drag(e); };
  61484. this._dropHandler = function (e) { _this.drop(e); };
  61485. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61486. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61487. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61488. }
  61489. };
  61490. FilesInput.prototype.dispose = function () {
  61491. if (!this._elementToMonitor) {
  61492. return;
  61493. }
  61494. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61495. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61496. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61497. };
  61498. FilesInput.prototype.renderFunction = function () {
  61499. if (this._additionalRenderLoopLogicCallback) {
  61500. this._additionalRenderLoopLogicCallback();
  61501. }
  61502. if (this._currentScene) {
  61503. if (this._textureLoadingCallback) {
  61504. var remaining = this._currentScene.getWaitingItemsCount();
  61505. if (remaining > 0) {
  61506. this._textureLoadingCallback(remaining);
  61507. }
  61508. }
  61509. this._currentScene.render();
  61510. }
  61511. };
  61512. FilesInput.prototype.drag = function (e) {
  61513. e.stopPropagation();
  61514. e.preventDefault();
  61515. };
  61516. FilesInput.prototype.drop = function (eventDrop) {
  61517. eventDrop.stopPropagation();
  61518. eventDrop.preventDefault();
  61519. this.loadFiles(eventDrop);
  61520. };
  61521. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61522. var _this = this;
  61523. var reader = folder.createReader();
  61524. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61525. reader.readEntries(function (entries) {
  61526. remaining.count += entries.length;
  61527. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61528. var entry = entries_1[_i];
  61529. if (entry.isFile) {
  61530. entry.file(function (file) {
  61531. file.correctName = relativePath + file.name;
  61532. files.push(file);
  61533. if (--remaining.count === 0) {
  61534. callback();
  61535. }
  61536. });
  61537. }
  61538. else if (entry.isDirectory) {
  61539. _this._traverseFolder(entry, files, remaining, callback);
  61540. }
  61541. }
  61542. if (--remaining.count) {
  61543. callback();
  61544. }
  61545. });
  61546. };
  61547. FilesInput.prototype._processFiles = function (files) {
  61548. for (var i = 0; i < files.length; i++) {
  61549. var name = files[i].correctName.toLowerCase();
  61550. var extension = name.split('.').pop();
  61551. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61552. continue;
  61553. }
  61554. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61555. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61556. this._sceneFileToLoad = files[i];
  61557. }
  61558. else {
  61559. FilesInput.FilesToLoad[name] = files[i];
  61560. }
  61561. }
  61562. };
  61563. FilesInput.prototype.loadFiles = function (event) {
  61564. var _this = this;
  61565. if (this._startingProcessingFilesCallback)
  61566. this._startingProcessingFilesCallback();
  61567. // Handling data transfer via drag'n'drop
  61568. if (event && event.dataTransfer && event.dataTransfer.files) {
  61569. this._filesToLoad = event.dataTransfer.files;
  61570. }
  61571. // Handling files from input files
  61572. if (event && event.target && event.target.files) {
  61573. this._filesToLoad = event.target.files;
  61574. }
  61575. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61576. var files_1 = new Array();
  61577. var folders = [];
  61578. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61579. for (var i = 0; i < this._filesToLoad.length; i++) {
  61580. var fileToLoad = this._filesToLoad[i];
  61581. var name_1 = fileToLoad.name.toLowerCase();
  61582. var entry = void 0;
  61583. fileToLoad.correctName = name_1;
  61584. if (items) {
  61585. var item = items[i];
  61586. if (item.getAsEntry) {
  61587. entry = item.getAsEntry();
  61588. }
  61589. else if (item.webkitGetAsEntry) {
  61590. entry = item.webkitGetAsEntry();
  61591. }
  61592. }
  61593. if (!entry) {
  61594. files_1.push(fileToLoad);
  61595. }
  61596. else {
  61597. if (entry.isDirectory) {
  61598. folders.push(entry);
  61599. }
  61600. else {
  61601. files_1.push(fileToLoad);
  61602. }
  61603. }
  61604. }
  61605. if (folders.length === 0) {
  61606. this._processFiles(files_1);
  61607. this._processReload();
  61608. }
  61609. else {
  61610. var remaining = { count: folders.length };
  61611. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61612. var folder = folders_1[_i];
  61613. this._traverseFolder(folder, files_1, remaining, function () {
  61614. _this._processFiles(files_1);
  61615. if (remaining.count === 0) {
  61616. _this._processReload();
  61617. }
  61618. });
  61619. }
  61620. }
  61621. }
  61622. };
  61623. FilesInput.prototype._processReload = function () {
  61624. if (this._onReloadCallback) {
  61625. this._onReloadCallback(this._sceneFileToLoad);
  61626. }
  61627. else {
  61628. this.reload();
  61629. }
  61630. };
  61631. FilesInput.prototype.reload = function () {
  61632. var _this = this;
  61633. // If a scene file has been provided
  61634. if (this._sceneFileToLoad) {
  61635. if (this._currentScene) {
  61636. if (BABYLON.Tools.errorsCount > 0) {
  61637. BABYLON.Tools.ClearLogCache();
  61638. }
  61639. this._engine.stopRenderLoop();
  61640. this._currentScene.dispose();
  61641. }
  61642. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61643. if (_this._progressCallback) {
  61644. _this._progressCallback(progress);
  61645. }
  61646. }).then(function (scene) {
  61647. _this._currentScene = scene;
  61648. if (_this._sceneLoadedCallback) {
  61649. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61650. }
  61651. // Wait for textures and shaders to be ready
  61652. _this._currentScene.executeWhenReady(function () {
  61653. _this._engine.runRenderLoop(function () {
  61654. _this.renderFunction();
  61655. });
  61656. });
  61657. }).catch(function (error) {
  61658. if (_this._errorCallback) {
  61659. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61660. }
  61661. });
  61662. }
  61663. else {
  61664. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61665. }
  61666. };
  61667. FilesInput.FilesToLoad = {};
  61668. return FilesInput;
  61669. }());
  61670. BABYLON.FilesInput = FilesInput;
  61671. })(BABYLON || (BABYLON = {}));
  61672. //# sourceMappingURL=babylon.filesInput.js.map
  61673. var BABYLON;
  61674. (function (BABYLON) {
  61675. /**
  61676. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61677. * The underlying implementation relies on an associative array to ensure the best performances.
  61678. * The value can be anything including 'null' but except 'undefined'
  61679. */
  61680. var StringDictionary = /** @class */ (function () {
  61681. function StringDictionary() {
  61682. this._count = 0;
  61683. this._data = {};
  61684. }
  61685. /**
  61686. * This will clear this dictionary and copy the content from the 'source' one.
  61687. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61688. * @param source the dictionary to take the content from and copy to this dictionary
  61689. */
  61690. StringDictionary.prototype.copyFrom = function (source) {
  61691. var _this = this;
  61692. this.clear();
  61693. source.forEach(function (t, v) { return _this.add(t, v); });
  61694. };
  61695. /**
  61696. * Get a value based from its key
  61697. * @param key the given key to get the matching value from
  61698. * @return the value if found, otherwise undefined is returned
  61699. */
  61700. StringDictionary.prototype.get = function (key) {
  61701. var val = this._data[key];
  61702. if (val !== undefined) {
  61703. return val;
  61704. }
  61705. return undefined;
  61706. };
  61707. /**
  61708. * Get a value from its key or add it if it doesn't exist.
  61709. * This method will ensure you that a given key/data will be present in the dictionary.
  61710. * @param key the given key to get the matching value from
  61711. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61712. * The factory will only be invoked if there's no data for the given key.
  61713. * @return the value corresponding to the key.
  61714. */
  61715. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61716. var val = this.get(key);
  61717. if (val !== undefined) {
  61718. return val;
  61719. }
  61720. val = factory(key);
  61721. if (val) {
  61722. this.add(key, val);
  61723. }
  61724. return val;
  61725. };
  61726. /**
  61727. * Get a value from its key if present in the dictionary otherwise add it
  61728. * @param key the key to get the value from
  61729. * @param val if there's no such key/value pair in the dictionary add it with this value
  61730. * @return the value corresponding to the key
  61731. */
  61732. StringDictionary.prototype.getOrAdd = function (key, val) {
  61733. var curVal = this.get(key);
  61734. if (curVal !== undefined) {
  61735. return curVal;
  61736. }
  61737. this.add(key, val);
  61738. return val;
  61739. };
  61740. /**
  61741. * Check if there's a given key in the dictionary
  61742. * @param key the key to check for
  61743. * @return true if the key is present, false otherwise
  61744. */
  61745. StringDictionary.prototype.contains = function (key) {
  61746. return this._data[key] !== undefined;
  61747. };
  61748. /**
  61749. * Add a new key and its corresponding value
  61750. * @param key the key to add
  61751. * @param value the value corresponding to the key
  61752. * @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
  61753. */
  61754. StringDictionary.prototype.add = function (key, value) {
  61755. if (this._data[key] !== undefined) {
  61756. return false;
  61757. }
  61758. this._data[key] = value;
  61759. ++this._count;
  61760. return true;
  61761. };
  61762. StringDictionary.prototype.set = function (key, value) {
  61763. if (this._data[key] === undefined) {
  61764. return false;
  61765. }
  61766. this._data[key] = value;
  61767. return true;
  61768. };
  61769. /**
  61770. * Get the element of the given key and remove it from the dictionary
  61771. * @param key
  61772. */
  61773. StringDictionary.prototype.getAndRemove = function (key) {
  61774. var val = this.get(key);
  61775. if (val !== undefined) {
  61776. delete this._data[key];
  61777. --this._count;
  61778. return val;
  61779. }
  61780. return null;
  61781. };
  61782. /**
  61783. * Remove a key/value from the dictionary.
  61784. * @param key the key to remove
  61785. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61786. */
  61787. StringDictionary.prototype.remove = function (key) {
  61788. if (this.contains(key)) {
  61789. delete this._data[key];
  61790. --this._count;
  61791. return true;
  61792. }
  61793. return false;
  61794. };
  61795. /**
  61796. * Clear the whole content of the dictionary
  61797. */
  61798. StringDictionary.prototype.clear = function () {
  61799. this._data = {};
  61800. this._count = 0;
  61801. };
  61802. Object.defineProperty(StringDictionary.prototype, "count", {
  61803. get: function () {
  61804. return this._count;
  61805. },
  61806. enumerable: true,
  61807. configurable: true
  61808. });
  61809. /**
  61810. * Execute a callback on each key/val of the dictionary.
  61811. * Note that you can remove any element in this dictionary in the callback implementation
  61812. * @param callback the callback to execute on a given key/value pair
  61813. */
  61814. StringDictionary.prototype.forEach = function (callback) {
  61815. for (var cur in this._data) {
  61816. var val = this._data[cur];
  61817. callback(cur, val);
  61818. }
  61819. };
  61820. /**
  61821. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61822. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61823. * Note that you can remove any element in this dictionary in the callback implementation
  61824. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61825. */
  61826. StringDictionary.prototype.first = function (callback) {
  61827. for (var cur in this._data) {
  61828. var val = this._data[cur];
  61829. var res = callback(cur, val);
  61830. if (res) {
  61831. return res;
  61832. }
  61833. }
  61834. return null;
  61835. };
  61836. return StringDictionary;
  61837. }());
  61838. BABYLON.StringDictionary = StringDictionary;
  61839. })(BABYLON || (BABYLON = {}));
  61840. //# sourceMappingURL=babylon.stringDictionary.js.map
  61841. var BABYLON;
  61842. (function (BABYLON) {
  61843. var Tags = /** @class */ (function () {
  61844. function Tags() {
  61845. }
  61846. Tags.EnableFor = function (obj) {
  61847. obj._tags = obj._tags || {};
  61848. obj.hasTags = function () {
  61849. return Tags.HasTags(obj);
  61850. };
  61851. obj.addTags = function (tagsString) {
  61852. return Tags.AddTagsTo(obj, tagsString);
  61853. };
  61854. obj.removeTags = function (tagsString) {
  61855. return Tags.RemoveTagsFrom(obj, tagsString);
  61856. };
  61857. obj.matchesTagsQuery = function (tagsQuery) {
  61858. return Tags.MatchesQuery(obj, tagsQuery);
  61859. };
  61860. };
  61861. Tags.DisableFor = function (obj) {
  61862. delete obj._tags;
  61863. delete obj.hasTags;
  61864. delete obj.addTags;
  61865. delete obj.removeTags;
  61866. delete obj.matchesTagsQuery;
  61867. };
  61868. Tags.HasTags = function (obj) {
  61869. if (!obj._tags) {
  61870. return false;
  61871. }
  61872. return !BABYLON.Tools.IsEmpty(obj._tags);
  61873. };
  61874. Tags.GetTags = function (obj, asString) {
  61875. if (asString === void 0) { asString = true; }
  61876. if (!obj._tags) {
  61877. return null;
  61878. }
  61879. if (asString) {
  61880. var tagsArray = [];
  61881. for (var tag in obj._tags) {
  61882. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61883. tagsArray.push(tag);
  61884. }
  61885. }
  61886. return tagsArray.join(" ");
  61887. }
  61888. else {
  61889. return obj._tags;
  61890. }
  61891. };
  61892. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61893. // a tag cannot start with '||', '&&', and '!'
  61894. // it cannot contain whitespaces
  61895. Tags.AddTagsTo = function (obj, tagsString) {
  61896. if (!tagsString) {
  61897. return;
  61898. }
  61899. if (typeof tagsString !== "string") {
  61900. return;
  61901. }
  61902. var tags = tagsString.split(" ");
  61903. tags.forEach(function (tag, index, array) {
  61904. Tags._AddTagTo(obj, tag);
  61905. });
  61906. };
  61907. Tags._AddTagTo = function (obj, tag) {
  61908. tag = tag.trim();
  61909. if (tag === "" || tag === "true" || tag === "false") {
  61910. return;
  61911. }
  61912. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61913. return;
  61914. }
  61915. Tags.EnableFor(obj);
  61916. obj._tags[tag] = true;
  61917. };
  61918. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61919. if (!Tags.HasTags(obj)) {
  61920. return;
  61921. }
  61922. var tags = tagsString.split(" ");
  61923. for (var t in tags) {
  61924. Tags._RemoveTagFrom(obj, tags[t]);
  61925. }
  61926. };
  61927. Tags._RemoveTagFrom = function (obj, tag) {
  61928. delete obj._tags[tag];
  61929. };
  61930. Tags.MatchesQuery = function (obj, tagsQuery) {
  61931. if (tagsQuery === undefined) {
  61932. return true;
  61933. }
  61934. if (tagsQuery === "") {
  61935. return Tags.HasTags(obj);
  61936. }
  61937. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61938. };
  61939. return Tags;
  61940. }());
  61941. BABYLON.Tags = Tags;
  61942. })(BABYLON || (BABYLON = {}));
  61943. //# sourceMappingURL=babylon.tags.js.map
  61944. var BABYLON;
  61945. (function (BABYLON) {
  61946. var AndOrNotEvaluator = /** @class */ (function () {
  61947. function AndOrNotEvaluator() {
  61948. }
  61949. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61950. if (!query.match(/\([^\(\)]*\)/g)) {
  61951. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61952. }
  61953. else {
  61954. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61955. // remove parenthesis
  61956. r = r.slice(1, r.length - 1);
  61957. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61958. });
  61959. }
  61960. if (query === "true") {
  61961. return true;
  61962. }
  61963. if (query === "false") {
  61964. return false;
  61965. }
  61966. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61967. };
  61968. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61969. evaluateCallback = evaluateCallback || (function (r) {
  61970. return r === "true" ? true : false;
  61971. });
  61972. var result;
  61973. var or = parenthesisContent.split("||");
  61974. for (var i in or) {
  61975. if (or.hasOwnProperty(i)) {
  61976. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61977. var and = ori.split("&&");
  61978. if (and.length > 1) {
  61979. for (var j = 0; j < and.length; ++j) {
  61980. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61981. if (andj !== "true" && andj !== "false") {
  61982. if (andj[0] === "!") {
  61983. result = !evaluateCallback(andj.substring(1));
  61984. }
  61985. else {
  61986. result = evaluateCallback(andj);
  61987. }
  61988. }
  61989. else {
  61990. result = andj === "true" ? true : false;
  61991. }
  61992. if (!result) {
  61993. ori = "false";
  61994. break;
  61995. }
  61996. }
  61997. }
  61998. if (result || ori === "true") {
  61999. result = true;
  62000. break;
  62001. }
  62002. // result equals false (or undefined)
  62003. if (ori !== "true" && ori !== "false") {
  62004. if (ori[0] === "!") {
  62005. result = !evaluateCallback(ori.substring(1));
  62006. }
  62007. else {
  62008. result = evaluateCallback(ori);
  62009. }
  62010. }
  62011. else {
  62012. result = ori === "true" ? true : false;
  62013. }
  62014. }
  62015. }
  62016. // the whole parenthesis scope is replaced by 'true' or 'false'
  62017. return result ? "true" : "false";
  62018. };
  62019. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62020. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62021. // remove whitespaces
  62022. r = r.replace(/[\s]/g, function () { return ""; });
  62023. return r.length % 2 ? "!" : "";
  62024. });
  62025. booleanString = booleanString.trim();
  62026. if (booleanString === "!true") {
  62027. booleanString = "false";
  62028. }
  62029. else if (booleanString === "!false") {
  62030. booleanString = "true";
  62031. }
  62032. return booleanString;
  62033. };
  62034. return AndOrNotEvaluator;
  62035. }());
  62036. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62037. })(BABYLON || (BABYLON = {}));
  62038. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62039. var BABYLON;
  62040. (function (BABYLON) {
  62041. var Database = /** @class */ (function () {
  62042. function Database(urlToScene, callbackManifestChecked) {
  62043. // Handling various flavors of prefixed version of IndexedDB
  62044. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62045. this.callbackManifestChecked = callbackManifestChecked;
  62046. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62047. this.db = null;
  62048. this._enableSceneOffline = false;
  62049. this._enableTexturesOffline = false;
  62050. this.manifestVersionFound = 0;
  62051. this.mustUpdateRessources = false;
  62052. this.hasReachedQuota = false;
  62053. if (!Database.IDBStorageEnabled) {
  62054. this.callbackManifestChecked(true);
  62055. }
  62056. else {
  62057. this.checkManifestFile();
  62058. }
  62059. }
  62060. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62061. get: function () {
  62062. return this._enableSceneOffline;
  62063. },
  62064. enumerable: true,
  62065. configurable: true
  62066. });
  62067. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62068. get: function () {
  62069. return this._enableTexturesOffline;
  62070. },
  62071. enumerable: true,
  62072. configurable: true
  62073. });
  62074. Database.prototype.checkManifestFile = function () {
  62075. var _this = this;
  62076. var noManifestFile = function () {
  62077. _this._enableSceneOffline = false;
  62078. _this._enableTexturesOffline = false;
  62079. _this.callbackManifestChecked(false);
  62080. };
  62081. var timeStampUsed = false;
  62082. var manifestURL = this.currentSceneUrl + ".manifest";
  62083. var xhr = new XMLHttpRequest();
  62084. if (navigator.onLine) {
  62085. // Adding a timestamp to by-pass browsers' cache
  62086. timeStampUsed = true;
  62087. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62088. }
  62089. xhr.open("GET", manifestURL, true);
  62090. xhr.addEventListener("load", function () {
  62091. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62092. try {
  62093. var manifestFile = JSON.parse(xhr.response);
  62094. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62095. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62096. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62097. _this.manifestVersionFound = manifestFile.version;
  62098. }
  62099. if (_this.callbackManifestChecked) {
  62100. _this.callbackManifestChecked(true);
  62101. }
  62102. }
  62103. catch (ex) {
  62104. noManifestFile();
  62105. }
  62106. }
  62107. else {
  62108. noManifestFile();
  62109. }
  62110. }, false);
  62111. xhr.addEventListener("error", function (event) {
  62112. if (timeStampUsed) {
  62113. timeStampUsed = false;
  62114. // Let's retry without the timeStamp
  62115. // It could fail when coupled with HTML5 Offline API
  62116. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62117. xhr.open("GET", retryManifestURL, true);
  62118. xhr.send();
  62119. }
  62120. else {
  62121. noManifestFile();
  62122. }
  62123. }, false);
  62124. try {
  62125. xhr.send();
  62126. }
  62127. catch (ex) {
  62128. BABYLON.Tools.Error("Error on XHR send request.");
  62129. this.callbackManifestChecked(false);
  62130. }
  62131. };
  62132. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62133. var _this = this;
  62134. var handleError = function () {
  62135. _this.isSupported = false;
  62136. if (errorCallback)
  62137. errorCallback();
  62138. };
  62139. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62140. // Your browser doesn't support IndexedDB
  62141. this.isSupported = false;
  62142. if (errorCallback)
  62143. errorCallback();
  62144. }
  62145. else {
  62146. // If the DB hasn't been opened or created yet
  62147. if (!this.db) {
  62148. this.hasReachedQuota = false;
  62149. this.isSupported = true;
  62150. var request = this.idbFactory.open("babylonjs", 1);
  62151. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62152. request.onerror = function (event) {
  62153. handleError();
  62154. };
  62155. // executes when a version change transaction cannot complete due to other active transactions
  62156. request.onblocked = function (event) {
  62157. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62158. handleError();
  62159. };
  62160. // DB has been opened successfully
  62161. request.onsuccess = function (event) {
  62162. _this.db = request.result;
  62163. successCallback();
  62164. };
  62165. // Initialization of the DB. Creating Scenes & Textures stores
  62166. request.onupgradeneeded = function (event) {
  62167. _this.db = (event.target).result;
  62168. if (_this.db) {
  62169. try {
  62170. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62171. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62172. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62173. }
  62174. catch (ex) {
  62175. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62176. handleError();
  62177. }
  62178. }
  62179. };
  62180. }
  62181. else {
  62182. if (successCallback)
  62183. successCallback();
  62184. }
  62185. }
  62186. };
  62187. Database.prototype.loadImageFromDB = function (url, image) {
  62188. var _this = this;
  62189. var completeURL = Database.ReturnFullUrlLocation(url);
  62190. var saveAndLoadImage = function () {
  62191. if (!_this.hasReachedQuota && _this.db !== null) {
  62192. // the texture is not yet in the DB, let's try to save it
  62193. _this._saveImageIntoDBAsync(completeURL, image);
  62194. }
  62195. else {
  62196. image.src = url;
  62197. }
  62198. };
  62199. if (!this.mustUpdateRessources) {
  62200. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62201. }
  62202. else {
  62203. saveAndLoadImage();
  62204. }
  62205. };
  62206. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62207. if (this.isSupported && this.db !== null) {
  62208. var texture;
  62209. var transaction = this.db.transaction(["textures"]);
  62210. transaction.onabort = function (event) {
  62211. image.src = url;
  62212. };
  62213. transaction.oncomplete = function (event) {
  62214. var blobTextureURL;
  62215. if (texture) {
  62216. var URL = window.URL || window.webkitURL;
  62217. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62218. image.onerror = function () {
  62219. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62220. image.src = url;
  62221. };
  62222. image.src = blobTextureURL;
  62223. }
  62224. else {
  62225. notInDBCallback();
  62226. }
  62227. };
  62228. var getRequest = transaction.objectStore("textures").get(url);
  62229. getRequest.onsuccess = function (event) {
  62230. texture = (event.target).result;
  62231. };
  62232. getRequest.onerror = function (event) {
  62233. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62234. image.src = url;
  62235. };
  62236. }
  62237. else {
  62238. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62239. image.src = url;
  62240. }
  62241. };
  62242. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62243. var _this = this;
  62244. if (this.isSupported) {
  62245. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62246. var generateBlobUrl = function () {
  62247. var blobTextureURL;
  62248. if (blob) {
  62249. var URL = window.URL || window.webkitURL;
  62250. try {
  62251. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62252. }
  62253. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62254. catch (ex) {
  62255. blobTextureURL = URL.createObjectURL(blob);
  62256. }
  62257. }
  62258. if (blobTextureURL) {
  62259. image.src = blobTextureURL;
  62260. }
  62261. };
  62262. if (Database.IsUASupportingBlobStorage) {
  62263. var xhr = new XMLHttpRequest(), blob;
  62264. xhr.open("GET", url, true);
  62265. xhr.responseType = "blob";
  62266. xhr.addEventListener("load", function () {
  62267. if (xhr.status === 200 && _this.db) {
  62268. // Blob as response (XHR2)
  62269. blob = xhr.response;
  62270. var transaction = _this.db.transaction(["textures"], "readwrite");
  62271. // the transaction could abort because of a QuotaExceededError error
  62272. transaction.onabort = function (event) {
  62273. try {
  62274. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62275. var srcElement = (event.srcElement || event.target);
  62276. var error = srcElement.error;
  62277. if (error && error.name === "QuotaExceededError") {
  62278. _this.hasReachedQuota = true;
  62279. }
  62280. }
  62281. catch (ex) { }
  62282. generateBlobUrl();
  62283. };
  62284. transaction.oncomplete = function (event) {
  62285. generateBlobUrl();
  62286. };
  62287. var newTexture = { textureUrl: url, data: blob };
  62288. try {
  62289. // Put the blob into the dabase
  62290. var addRequest = transaction.objectStore("textures").put(newTexture);
  62291. addRequest.onsuccess = function (event) {
  62292. };
  62293. addRequest.onerror = function (event) {
  62294. generateBlobUrl();
  62295. };
  62296. }
  62297. catch (ex) {
  62298. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62299. if (ex.code === 25) {
  62300. Database.IsUASupportingBlobStorage = false;
  62301. }
  62302. image.src = url;
  62303. }
  62304. }
  62305. else {
  62306. image.src = url;
  62307. }
  62308. }, false);
  62309. xhr.addEventListener("error", function (event) {
  62310. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62311. image.src = url;
  62312. }, false);
  62313. xhr.send();
  62314. }
  62315. else {
  62316. image.src = url;
  62317. }
  62318. }
  62319. else {
  62320. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62321. image.src = url;
  62322. }
  62323. };
  62324. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62325. var _this = this;
  62326. var updateVersion = function () {
  62327. // the version is not yet in the DB or we need to update it
  62328. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62329. };
  62330. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62331. };
  62332. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62333. var _this = this;
  62334. if (this.isSupported && this.db) {
  62335. var version;
  62336. try {
  62337. var transaction = this.db.transaction(["versions"]);
  62338. transaction.oncomplete = function (event) {
  62339. if (version) {
  62340. // If the version in the JSON file is > than the version in DB
  62341. if (_this.manifestVersionFound > version.data) {
  62342. _this.mustUpdateRessources = true;
  62343. updateInDBCallback();
  62344. }
  62345. else {
  62346. callback(version.data);
  62347. }
  62348. }
  62349. else {
  62350. _this.mustUpdateRessources = true;
  62351. updateInDBCallback();
  62352. }
  62353. };
  62354. transaction.onabort = function (event) {
  62355. callback(-1);
  62356. };
  62357. var getRequest = transaction.objectStore("versions").get(url);
  62358. getRequest.onsuccess = function (event) {
  62359. version = (event.target).result;
  62360. };
  62361. getRequest.onerror = function (event) {
  62362. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62363. callback(-1);
  62364. };
  62365. }
  62366. catch (ex) {
  62367. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62368. callback(-1);
  62369. }
  62370. }
  62371. else {
  62372. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62373. callback(-1);
  62374. }
  62375. };
  62376. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62377. var _this = this;
  62378. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62379. try {
  62380. // Open a transaction to the database
  62381. var transaction = this.db.transaction(["versions"], "readwrite");
  62382. // the transaction could abort because of a QuotaExceededError error
  62383. transaction.onabort = function (event) {
  62384. try {
  62385. var error = event.srcElement['error'];
  62386. if (error && error.name === "QuotaExceededError") {
  62387. _this.hasReachedQuota = true;
  62388. }
  62389. }
  62390. catch (ex) { }
  62391. callback(-1);
  62392. };
  62393. transaction.oncomplete = function (event) {
  62394. callback(_this.manifestVersionFound);
  62395. };
  62396. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62397. // Put the scene into the database
  62398. var addRequest = transaction.objectStore("versions").put(newVersion);
  62399. addRequest.onsuccess = function (event) {
  62400. };
  62401. addRequest.onerror = function (event) {
  62402. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62403. };
  62404. }
  62405. catch (ex) {
  62406. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62407. callback(-1);
  62408. }
  62409. }
  62410. else {
  62411. callback(-1);
  62412. }
  62413. };
  62414. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62415. var _this = this;
  62416. var completeUrl = Database.ReturnFullUrlLocation(url);
  62417. var saveAndLoadFile = function () {
  62418. // the scene is not yet in the DB, let's try to save it
  62419. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62420. };
  62421. this._checkVersionFromDB(completeUrl, function (version) {
  62422. if (version !== -1) {
  62423. if (!_this.mustUpdateRessources) {
  62424. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62425. }
  62426. else {
  62427. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62428. }
  62429. }
  62430. else {
  62431. if (errorCallback) {
  62432. errorCallback();
  62433. }
  62434. }
  62435. });
  62436. };
  62437. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62438. if (this.isSupported && this.db) {
  62439. var targetStore;
  62440. if (url.indexOf(".babylon") !== -1) {
  62441. targetStore = "scenes";
  62442. }
  62443. else {
  62444. targetStore = "textures";
  62445. }
  62446. var file;
  62447. var transaction = this.db.transaction([targetStore]);
  62448. transaction.oncomplete = function (event) {
  62449. if (file) {
  62450. callback(file.data);
  62451. }
  62452. else {
  62453. notInDBCallback();
  62454. }
  62455. };
  62456. transaction.onabort = function (event) {
  62457. notInDBCallback();
  62458. };
  62459. var getRequest = transaction.objectStore(targetStore).get(url);
  62460. getRequest.onsuccess = function (event) {
  62461. file = (event.target).result;
  62462. };
  62463. getRequest.onerror = function (event) {
  62464. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62465. notInDBCallback();
  62466. };
  62467. }
  62468. else {
  62469. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62470. callback();
  62471. }
  62472. };
  62473. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62474. var _this = this;
  62475. if (this.isSupported) {
  62476. var targetStore;
  62477. if (url.indexOf(".babylon") !== -1) {
  62478. targetStore = "scenes";
  62479. }
  62480. else {
  62481. targetStore = "textures";
  62482. }
  62483. // Create XHR
  62484. var xhr = new XMLHttpRequest();
  62485. var fileData;
  62486. xhr.open("GET", url, true);
  62487. if (useArrayBuffer) {
  62488. xhr.responseType = "arraybuffer";
  62489. }
  62490. if (progressCallback) {
  62491. xhr.onprogress = progressCallback;
  62492. }
  62493. xhr.addEventListener("load", function () {
  62494. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62495. // Blob as response (XHR2)
  62496. //fileData = xhr.responseText;
  62497. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62498. if (!_this.hasReachedQuota && _this.db) {
  62499. // Open a transaction to the database
  62500. var transaction = _this.db.transaction([targetStore], "readwrite");
  62501. // the transaction could abort because of a QuotaExceededError error
  62502. transaction.onabort = function (event) {
  62503. try {
  62504. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62505. var error = event.srcElement['error'];
  62506. if (error && error.name === "QuotaExceededError") {
  62507. _this.hasReachedQuota = true;
  62508. }
  62509. }
  62510. catch (ex) { }
  62511. callback(fileData);
  62512. };
  62513. transaction.oncomplete = function (event) {
  62514. callback(fileData);
  62515. };
  62516. var newFile;
  62517. if (targetStore === "scenes") {
  62518. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62519. }
  62520. else {
  62521. newFile = { textureUrl: url, data: fileData };
  62522. }
  62523. try {
  62524. // Put the scene into the database
  62525. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62526. addRequest.onsuccess = function (event) {
  62527. };
  62528. addRequest.onerror = function (event) {
  62529. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62530. };
  62531. }
  62532. catch (ex) {
  62533. callback(fileData);
  62534. }
  62535. }
  62536. else {
  62537. callback(fileData);
  62538. }
  62539. }
  62540. else {
  62541. callback();
  62542. }
  62543. }, false);
  62544. xhr.addEventListener("error", function (event) {
  62545. BABYLON.Tools.Error("error on XHR request.");
  62546. callback();
  62547. }, false);
  62548. xhr.send();
  62549. }
  62550. else {
  62551. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62552. callback();
  62553. }
  62554. };
  62555. Database.IsUASupportingBlobStorage = true;
  62556. Database.IDBStorageEnabled = true;
  62557. Database.parseURL = function (url) {
  62558. var a = document.createElement('a');
  62559. a.href = url;
  62560. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62561. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62562. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62563. return absLocation;
  62564. };
  62565. Database.ReturnFullUrlLocation = function (url) {
  62566. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62567. return (Database.parseURL(window.location.href) + url);
  62568. }
  62569. else {
  62570. return url;
  62571. }
  62572. };
  62573. return Database;
  62574. }());
  62575. BABYLON.Database = Database;
  62576. })(BABYLON || (BABYLON = {}));
  62577. //# sourceMappingURL=babylon.database.js.map
  62578. var BABYLON;
  62579. (function (BABYLON) {
  62580. var FresnelParameters = /** @class */ (function () {
  62581. function FresnelParameters() {
  62582. this._isEnabled = true;
  62583. this.leftColor = BABYLON.Color3.White();
  62584. this.rightColor = BABYLON.Color3.Black();
  62585. this.bias = 0;
  62586. this.power = 1;
  62587. }
  62588. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62589. get: function () {
  62590. return this._isEnabled;
  62591. },
  62592. set: function (value) {
  62593. if (this._isEnabled === value) {
  62594. return;
  62595. }
  62596. this._isEnabled = value;
  62597. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62598. },
  62599. enumerable: true,
  62600. configurable: true
  62601. });
  62602. FresnelParameters.prototype.clone = function () {
  62603. var newFresnelParameters = new FresnelParameters();
  62604. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62605. return newFresnelParameters;
  62606. };
  62607. FresnelParameters.prototype.serialize = function () {
  62608. var serializationObject = {};
  62609. serializationObject.isEnabled = this.isEnabled;
  62610. serializationObject.leftColor = this.leftColor;
  62611. serializationObject.rightColor = this.rightColor;
  62612. serializationObject.bias = this.bias;
  62613. serializationObject.power = this.power;
  62614. return serializationObject;
  62615. };
  62616. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62617. var fresnelParameters = new FresnelParameters();
  62618. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62619. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62620. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62621. fresnelParameters.bias = parsedFresnelParameters.bias;
  62622. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62623. return fresnelParameters;
  62624. };
  62625. return FresnelParameters;
  62626. }());
  62627. BABYLON.FresnelParameters = FresnelParameters;
  62628. })(BABYLON || (BABYLON = {}));
  62629. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62630. var BABYLON;
  62631. (function (BABYLON) {
  62632. var MultiMaterial = /** @class */ (function (_super) {
  62633. __extends(MultiMaterial, _super);
  62634. function MultiMaterial(name, scene) {
  62635. var _this = _super.call(this, name, scene, true) || this;
  62636. scene.multiMaterials.push(_this);
  62637. _this.subMaterials = new Array();
  62638. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62639. return _this;
  62640. }
  62641. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62642. get: function () {
  62643. return this._subMaterials;
  62644. },
  62645. set: function (value) {
  62646. this._subMaterials = value;
  62647. this._hookArray(value);
  62648. },
  62649. enumerable: true,
  62650. configurable: true
  62651. });
  62652. MultiMaterial.prototype._hookArray = function (array) {
  62653. var _this = this;
  62654. var oldPush = array.push;
  62655. array.push = function () {
  62656. var items = [];
  62657. for (var _i = 0; _i < arguments.length; _i++) {
  62658. items[_i] = arguments[_i];
  62659. }
  62660. var result = oldPush.apply(array, items);
  62661. _this._markAllSubMeshesAsTexturesDirty();
  62662. return result;
  62663. };
  62664. var oldSplice = array.splice;
  62665. array.splice = function (index, deleteCount) {
  62666. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62667. _this._markAllSubMeshesAsTexturesDirty();
  62668. return deleted;
  62669. };
  62670. };
  62671. // Properties
  62672. MultiMaterial.prototype.getSubMaterial = function (index) {
  62673. if (index < 0 || index >= this.subMaterials.length) {
  62674. return this.getScene().defaultMaterial;
  62675. }
  62676. return this.subMaterials[index];
  62677. };
  62678. MultiMaterial.prototype.getActiveTextures = function () {
  62679. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62680. if (subMaterial) {
  62681. return subMaterial.getActiveTextures();
  62682. }
  62683. else {
  62684. return [];
  62685. }
  62686. }));
  62687. var _a;
  62688. };
  62689. // Methods
  62690. MultiMaterial.prototype.getClassName = function () {
  62691. return "MultiMaterial";
  62692. };
  62693. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62694. for (var index = 0; index < this.subMaterials.length; index++) {
  62695. var subMaterial = this.subMaterials[index];
  62696. if (subMaterial) {
  62697. if (subMaterial.storeEffectOnSubMeshes) {
  62698. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62699. return false;
  62700. }
  62701. continue;
  62702. }
  62703. if (!subMaterial.isReady(mesh)) {
  62704. return false;
  62705. }
  62706. }
  62707. }
  62708. return true;
  62709. };
  62710. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62711. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62712. for (var index = 0; index < this.subMaterials.length; index++) {
  62713. var subMaterial = null;
  62714. var current = this.subMaterials[index];
  62715. if (cloneChildren && current) {
  62716. subMaterial = current.clone(name + "-" + current.name);
  62717. }
  62718. else {
  62719. subMaterial = this.subMaterials[index];
  62720. }
  62721. newMultiMaterial.subMaterials.push(subMaterial);
  62722. }
  62723. return newMultiMaterial;
  62724. };
  62725. MultiMaterial.prototype.serialize = function () {
  62726. var serializationObject = {};
  62727. serializationObject.name = this.name;
  62728. serializationObject.id = this.id;
  62729. if (BABYLON.Tags) {
  62730. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62731. }
  62732. serializationObject.materials = [];
  62733. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62734. var subMat = this.subMaterials[matIndex];
  62735. if (subMat) {
  62736. serializationObject.materials.push(subMat.id);
  62737. }
  62738. else {
  62739. serializationObject.materials.push(null);
  62740. }
  62741. }
  62742. return serializationObject;
  62743. };
  62744. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62745. var scene = this.getScene();
  62746. if (!scene) {
  62747. return;
  62748. }
  62749. var index = scene.multiMaterials.indexOf(this);
  62750. if (index >= 0) {
  62751. scene.multiMaterials.splice(index, 1);
  62752. }
  62753. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62754. };
  62755. return MultiMaterial;
  62756. }(BABYLON.Material));
  62757. BABYLON.MultiMaterial = MultiMaterial;
  62758. })(BABYLON || (BABYLON = {}));
  62759. //# sourceMappingURL=babylon.multiMaterial.js.map
  62760. var BABYLON;
  62761. (function (BABYLON) {
  62762. var FreeCameraTouchInput = /** @class */ (function () {
  62763. function FreeCameraTouchInput() {
  62764. this._offsetX = null;
  62765. this._offsetY = null;
  62766. this._pointerPressed = new Array();
  62767. this.touchAngularSensibility = 200000.0;
  62768. this.touchMoveSensibility = 250.0;
  62769. }
  62770. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62771. var _this = this;
  62772. var previousPosition = null;
  62773. if (this._pointerInput === undefined) {
  62774. this._onLostFocus = function (evt) {
  62775. _this._offsetX = null;
  62776. _this._offsetY = null;
  62777. };
  62778. this._pointerInput = function (p, s) {
  62779. var evt = p.event;
  62780. if (evt.pointerType === "mouse") {
  62781. return;
  62782. }
  62783. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62784. if (!noPreventDefault) {
  62785. evt.preventDefault();
  62786. }
  62787. _this._pointerPressed.push(evt.pointerId);
  62788. if (_this._pointerPressed.length !== 1) {
  62789. return;
  62790. }
  62791. previousPosition = {
  62792. x: evt.clientX,
  62793. y: evt.clientY
  62794. };
  62795. }
  62796. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62797. if (!noPreventDefault) {
  62798. evt.preventDefault();
  62799. }
  62800. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62801. if (index === -1) {
  62802. return;
  62803. }
  62804. _this._pointerPressed.splice(index, 1);
  62805. if (index != 0) {
  62806. return;
  62807. }
  62808. previousPosition = null;
  62809. _this._offsetX = null;
  62810. _this._offsetY = null;
  62811. }
  62812. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62813. if (!noPreventDefault) {
  62814. evt.preventDefault();
  62815. }
  62816. if (!previousPosition) {
  62817. return;
  62818. }
  62819. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62820. if (index != 0) {
  62821. return;
  62822. }
  62823. _this._offsetX = evt.clientX - previousPosition.x;
  62824. _this._offsetY = -(evt.clientY - previousPosition.y);
  62825. }
  62826. };
  62827. }
  62828. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62829. if (this._onLostFocus) {
  62830. element.addEventListener("blur", this._onLostFocus);
  62831. }
  62832. };
  62833. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62834. if (this._pointerInput && element) {
  62835. if (this._observer) {
  62836. this.camera.getScene().onPointerObservable.remove(this._observer);
  62837. this._observer = null;
  62838. }
  62839. if (this._onLostFocus) {
  62840. element.removeEventListener("blur", this._onLostFocus);
  62841. this._onLostFocus = null;
  62842. }
  62843. this._pointerPressed = [];
  62844. this._offsetX = null;
  62845. this._offsetY = null;
  62846. }
  62847. };
  62848. FreeCameraTouchInput.prototype.checkInputs = function () {
  62849. if (this._offsetX && this._offsetY) {
  62850. var camera = this.camera;
  62851. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62852. if (this._pointerPressed.length > 1) {
  62853. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62854. }
  62855. else {
  62856. var speed = camera._computeLocalCameraSpeed();
  62857. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62858. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62859. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62860. }
  62861. }
  62862. };
  62863. FreeCameraTouchInput.prototype.getClassName = function () {
  62864. return "FreeCameraTouchInput";
  62865. };
  62866. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62867. return "touch";
  62868. };
  62869. __decorate([
  62870. BABYLON.serialize()
  62871. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62872. __decorate([
  62873. BABYLON.serialize()
  62874. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62875. return FreeCameraTouchInput;
  62876. }());
  62877. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62878. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62879. })(BABYLON || (BABYLON = {}));
  62880. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62881. var BABYLON;
  62882. (function (BABYLON) {
  62883. // We're mainly based on the logic defined into the FreeCamera code
  62884. var TouchCamera = /** @class */ (function (_super) {
  62885. __extends(TouchCamera, _super);
  62886. //-- end properties for backward compatibility for inputs
  62887. function TouchCamera(name, position, scene) {
  62888. var _this = _super.call(this, name, position, scene) || this;
  62889. _this.inputs.addTouch();
  62890. _this._setupInputs();
  62891. return _this;
  62892. }
  62893. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62894. //-- Begin properties for backward compatibility for inputs
  62895. get: function () {
  62896. var touch = this.inputs.attached["touch"];
  62897. if (touch)
  62898. return touch.touchAngularSensibility;
  62899. return 0;
  62900. },
  62901. set: function (value) {
  62902. var touch = this.inputs.attached["touch"];
  62903. if (touch)
  62904. touch.touchAngularSensibility = value;
  62905. },
  62906. enumerable: true,
  62907. configurable: true
  62908. });
  62909. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62910. get: function () {
  62911. var touch = this.inputs.attached["touch"];
  62912. if (touch)
  62913. return touch.touchMoveSensibility;
  62914. return 0;
  62915. },
  62916. set: function (value) {
  62917. var touch = this.inputs.attached["touch"];
  62918. if (touch)
  62919. touch.touchMoveSensibility = value;
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. TouchCamera.prototype.getClassName = function () {
  62925. return "TouchCamera";
  62926. };
  62927. TouchCamera.prototype._setupInputs = function () {
  62928. var mouse = this.inputs.attached["mouse"];
  62929. if (mouse) {
  62930. mouse.touchEnabled = false;
  62931. }
  62932. };
  62933. return TouchCamera;
  62934. }(BABYLON.FreeCamera));
  62935. BABYLON.TouchCamera = TouchCamera;
  62936. })(BABYLON || (BABYLON = {}));
  62937. //# sourceMappingURL=babylon.touchCamera.js.map
  62938. var BABYLON;
  62939. (function (BABYLON) {
  62940. var ProceduralTexture = /** @class */ (function (_super) {
  62941. __extends(ProceduralTexture, _super);
  62942. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62943. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62945. if (isCube === void 0) { isCube = false; }
  62946. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62947. _this.isCube = isCube;
  62948. _this.isEnabled = true;
  62949. _this._currentRefreshId = -1;
  62950. _this._refreshRate = 1;
  62951. _this._vertexBuffers = {};
  62952. _this._uniforms = new Array();
  62953. _this._samplers = new Array();
  62954. _this._textures = {};
  62955. _this._floats = {};
  62956. _this._floatsArrays = {};
  62957. _this._colors3 = {};
  62958. _this._colors4 = {};
  62959. _this._vectors2 = {};
  62960. _this._vectors3 = {};
  62961. _this._matrices = {};
  62962. _this._fallbackTextureUsed = false;
  62963. scene._proceduralTextures.push(_this);
  62964. _this._engine = scene.getEngine();
  62965. _this.name = name;
  62966. _this.isRenderTarget = true;
  62967. _this._size = size;
  62968. _this._generateMipMaps = generateMipMaps;
  62969. _this.setFragment(fragment);
  62970. _this._fallbackTexture = fallbackTexture;
  62971. if (isCube) {
  62972. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62973. _this.setFloat("face", 0);
  62974. }
  62975. else {
  62976. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62977. }
  62978. // VBO
  62979. var vertices = [];
  62980. vertices.push(1, 1);
  62981. vertices.push(-1, 1);
  62982. vertices.push(-1, -1);
  62983. vertices.push(1, -1);
  62984. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62985. _this._createIndexBuffer();
  62986. return _this;
  62987. }
  62988. ProceduralTexture.prototype._createIndexBuffer = function () {
  62989. var engine = this._engine;
  62990. // Indices
  62991. var indices = [];
  62992. indices.push(0);
  62993. indices.push(1);
  62994. indices.push(2);
  62995. indices.push(0);
  62996. indices.push(2);
  62997. indices.push(3);
  62998. this._indexBuffer = engine.createIndexBuffer(indices);
  62999. };
  63000. ProceduralTexture.prototype._rebuild = function () {
  63001. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63002. if (vb) {
  63003. vb._rebuild();
  63004. }
  63005. this._createIndexBuffer();
  63006. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63007. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63008. }
  63009. };
  63010. ProceduralTexture.prototype.reset = function () {
  63011. if (this._effect === undefined) {
  63012. return;
  63013. }
  63014. var engine = this._engine;
  63015. engine._releaseEffect(this._effect);
  63016. };
  63017. ProceduralTexture.prototype.isReady = function () {
  63018. var _this = this;
  63019. var engine = this._engine;
  63020. var shaders;
  63021. if (!this._fragment) {
  63022. return false;
  63023. }
  63024. if (this._fallbackTextureUsed) {
  63025. return true;
  63026. }
  63027. if (this._fragment.fragmentElement !== undefined) {
  63028. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63029. }
  63030. else {
  63031. shaders = { vertex: "procedural", fragment: this._fragment };
  63032. }
  63033. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63034. _this.releaseInternalTexture();
  63035. if (_this._fallbackTexture) {
  63036. _this._texture = _this._fallbackTexture._texture;
  63037. if (_this._texture) {
  63038. _this._texture.incrementReferences();
  63039. }
  63040. }
  63041. _this._fallbackTextureUsed = true;
  63042. });
  63043. return this._effect.isReady();
  63044. };
  63045. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63046. this._currentRefreshId = -1;
  63047. };
  63048. ProceduralTexture.prototype.setFragment = function (fragment) {
  63049. this._fragment = fragment;
  63050. };
  63051. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63052. get: function () {
  63053. return this._refreshRate;
  63054. },
  63055. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63056. set: function (value) {
  63057. this._refreshRate = value;
  63058. this.resetRefreshCounter();
  63059. },
  63060. enumerable: true,
  63061. configurable: true
  63062. });
  63063. ProceduralTexture.prototype._shouldRender = function () {
  63064. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63065. return false;
  63066. }
  63067. if (this._fallbackTextureUsed) {
  63068. return false;
  63069. }
  63070. if (this._currentRefreshId === -1) {
  63071. this._currentRefreshId = 1;
  63072. return true;
  63073. }
  63074. if (this.refreshRate === this._currentRefreshId) {
  63075. this._currentRefreshId = 1;
  63076. return true;
  63077. }
  63078. this._currentRefreshId++;
  63079. return false;
  63080. };
  63081. ProceduralTexture.prototype.getRenderSize = function () {
  63082. return this._size;
  63083. };
  63084. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63085. if (this._fallbackTextureUsed) {
  63086. return;
  63087. }
  63088. this.releaseInternalTexture();
  63089. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63090. };
  63091. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63092. if (this._uniforms.indexOf(uniformName) === -1) {
  63093. this._uniforms.push(uniformName);
  63094. }
  63095. };
  63096. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63097. if (this._samplers.indexOf(name) === -1) {
  63098. this._samplers.push(name);
  63099. }
  63100. this._textures[name] = texture;
  63101. return this;
  63102. };
  63103. ProceduralTexture.prototype.setFloat = function (name, value) {
  63104. this._checkUniform(name);
  63105. this._floats[name] = value;
  63106. return this;
  63107. };
  63108. ProceduralTexture.prototype.setFloats = function (name, value) {
  63109. this._checkUniform(name);
  63110. this._floatsArrays[name] = value;
  63111. return this;
  63112. };
  63113. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63114. this._checkUniform(name);
  63115. this._colors3[name] = value;
  63116. return this;
  63117. };
  63118. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63119. this._checkUniform(name);
  63120. this._colors4[name] = value;
  63121. return this;
  63122. };
  63123. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63124. this._checkUniform(name);
  63125. this._vectors2[name] = value;
  63126. return this;
  63127. };
  63128. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63129. this._checkUniform(name);
  63130. this._vectors3[name] = value;
  63131. return this;
  63132. };
  63133. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63134. this._checkUniform(name);
  63135. this._matrices[name] = value;
  63136. return this;
  63137. };
  63138. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63139. var scene = this.getScene();
  63140. if (!scene) {
  63141. return;
  63142. }
  63143. var engine = this._engine;
  63144. // Render
  63145. engine.enableEffect(this._effect);
  63146. engine.setState(false);
  63147. // Texture
  63148. for (var name in this._textures) {
  63149. this._effect.setTexture(name, this._textures[name]);
  63150. }
  63151. // Float
  63152. for (name in this._floats) {
  63153. this._effect.setFloat(name, this._floats[name]);
  63154. }
  63155. // Floats
  63156. for (name in this._floatsArrays) {
  63157. this._effect.setArray(name, this._floatsArrays[name]);
  63158. }
  63159. // Color3
  63160. for (name in this._colors3) {
  63161. this._effect.setColor3(name, this._colors3[name]);
  63162. }
  63163. // Color4
  63164. for (name in this._colors4) {
  63165. var color = this._colors4[name];
  63166. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63167. }
  63168. // Vector2
  63169. for (name in this._vectors2) {
  63170. this._effect.setVector2(name, this._vectors2[name]);
  63171. }
  63172. // Vector3
  63173. for (name in this._vectors3) {
  63174. this._effect.setVector3(name, this._vectors3[name]);
  63175. }
  63176. // Matrix
  63177. for (name in this._matrices) {
  63178. this._effect.setMatrix(name, this._matrices[name]);
  63179. }
  63180. if (!this._texture) {
  63181. return;
  63182. }
  63183. if (this.isCube) {
  63184. for (var face = 0; face < 6; face++) {
  63185. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63186. // VBOs
  63187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63188. this._effect.setFloat("face", face);
  63189. // Clear
  63190. engine.clear(scene.clearColor, true, true, true);
  63191. // Draw order
  63192. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63193. // Mipmaps
  63194. if (face === 5) {
  63195. engine.generateMipMapsForCubemap(this._texture);
  63196. }
  63197. }
  63198. }
  63199. else {
  63200. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63201. // VBOs
  63202. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63203. // Clear
  63204. engine.clear(scene.clearColor, true, true, true);
  63205. // Draw order
  63206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63207. }
  63208. // Unbind
  63209. engine.unBindFramebuffer(this._texture, this.isCube);
  63210. if (this.onGenerated) {
  63211. this.onGenerated();
  63212. }
  63213. };
  63214. ProceduralTexture.prototype.clone = function () {
  63215. var textureSize = this.getSize();
  63216. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63217. // Base texture
  63218. newTexture.hasAlpha = this.hasAlpha;
  63219. newTexture.level = this.level;
  63220. // RenderTarget Texture
  63221. newTexture.coordinatesMode = this.coordinatesMode;
  63222. return newTexture;
  63223. };
  63224. ProceduralTexture.prototype.dispose = function () {
  63225. var scene = this.getScene();
  63226. if (!scene) {
  63227. return;
  63228. }
  63229. var index = scene._proceduralTextures.indexOf(this);
  63230. if (index >= 0) {
  63231. scene._proceduralTextures.splice(index, 1);
  63232. }
  63233. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63234. if (vertexBuffer) {
  63235. vertexBuffer.dispose();
  63236. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63237. }
  63238. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63239. this._indexBuffer = null;
  63240. }
  63241. _super.prototype.dispose.call(this);
  63242. };
  63243. return ProceduralTexture;
  63244. }(BABYLON.Texture));
  63245. BABYLON.ProceduralTexture = ProceduralTexture;
  63246. })(BABYLON || (BABYLON = {}));
  63247. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63248. var BABYLON;
  63249. (function (BABYLON) {
  63250. var CustomProceduralTexture = /** @class */ (function (_super) {
  63251. __extends(CustomProceduralTexture, _super);
  63252. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63253. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63254. _this._animate = true;
  63255. _this._time = 0;
  63256. _this._texturePath = texturePath;
  63257. //Try to load json
  63258. _this.loadJson(texturePath);
  63259. _this.refreshRate = 1;
  63260. return _this;
  63261. }
  63262. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63263. var _this = this;
  63264. var noConfigFile = function () {
  63265. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63266. try {
  63267. _this.setFragment(_this._texturePath);
  63268. }
  63269. catch (ex) {
  63270. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63271. }
  63272. };
  63273. var configFileUrl = jsonUrl + "/config.json";
  63274. var xhr = new XMLHttpRequest();
  63275. xhr.open("GET", configFileUrl, true);
  63276. xhr.addEventListener("load", function () {
  63277. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63278. try {
  63279. _this._config = JSON.parse(xhr.response);
  63280. _this.updateShaderUniforms();
  63281. _this.updateTextures();
  63282. _this.setFragment(_this._texturePath + "/custom");
  63283. _this._animate = _this._config.animate;
  63284. _this.refreshRate = _this._config.refreshrate;
  63285. }
  63286. catch (ex) {
  63287. noConfigFile();
  63288. }
  63289. }
  63290. else {
  63291. noConfigFile();
  63292. }
  63293. }, false);
  63294. xhr.addEventListener("error", function () {
  63295. noConfigFile();
  63296. }, false);
  63297. try {
  63298. xhr.send();
  63299. }
  63300. catch (ex) {
  63301. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63302. }
  63303. };
  63304. CustomProceduralTexture.prototype.isReady = function () {
  63305. if (!_super.prototype.isReady.call(this)) {
  63306. return false;
  63307. }
  63308. for (var name in this._textures) {
  63309. var texture = this._textures[name];
  63310. if (!texture.isReady()) {
  63311. return false;
  63312. }
  63313. }
  63314. return true;
  63315. };
  63316. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63317. var scene = this.getScene();
  63318. if (this._animate && scene) {
  63319. this._time += scene.getAnimationRatio() * 0.03;
  63320. this.updateShaderUniforms();
  63321. }
  63322. _super.prototype.render.call(this, useCameraPostProcess);
  63323. };
  63324. CustomProceduralTexture.prototype.updateTextures = function () {
  63325. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63326. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63327. }
  63328. };
  63329. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63330. if (this._config) {
  63331. for (var j = 0; j < this._config.uniforms.length; j++) {
  63332. var uniform = this._config.uniforms[j];
  63333. switch (uniform.type) {
  63334. case "float":
  63335. this.setFloat(uniform.name, uniform.value);
  63336. break;
  63337. case "color3":
  63338. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63339. break;
  63340. case "color4":
  63341. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63342. break;
  63343. case "vector2":
  63344. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63345. break;
  63346. case "vector3":
  63347. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63348. break;
  63349. }
  63350. }
  63351. }
  63352. this.setFloat("time", this._time);
  63353. };
  63354. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63355. get: function () {
  63356. return this._animate;
  63357. },
  63358. set: function (value) {
  63359. this._animate = value;
  63360. },
  63361. enumerable: true,
  63362. configurable: true
  63363. });
  63364. return CustomProceduralTexture;
  63365. }(BABYLON.ProceduralTexture));
  63366. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63367. })(BABYLON || (BABYLON = {}));
  63368. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63369. var BABYLON;
  63370. (function (BABYLON) {
  63371. var FreeCameraGamepadInput = /** @class */ (function () {
  63372. function FreeCameraGamepadInput() {
  63373. this.gamepadAngularSensibility = 200;
  63374. this.gamepadMoveSensibility = 40;
  63375. // private members
  63376. this._cameraTransform = BABYLON.Matrix.Identity();
  63377. this._deltaTransform = BABYLON.Vector3.Zero();
  63378. this._vector3 = BABYLON.Vector3.Zero();
  63379. this._vector2 = BABYLON.Vector2.Zero();
  63380. }
  63381. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63382. var _this = this;
  63383. var manager = this.camera.getScene().gamepadManager;
  63384. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63385. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63386. // prioritize XBOX gamepads.
  63387. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63388. _this.gamepad = gamepad;
  63389. }
  63390. }
  63391. });
  63392. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63393. if (_this.gamepad === gamepad) {
  63394. _this.gamepad = null;
  63395. }
  63396. });
  63397. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63398. };
  63399. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63400. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63401. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63402. this.gamepad = null;
  63403. };
  63404. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63405. if (this.gamepad && this.gamepad.leftStick) {
  63406. var camera = this.camera;
  63407. var LSValues = this.gamepad.leftStick;
  63408. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63409. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63410. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63411. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63412. var RSValues = this.gamepad.rightStick;
  63413. if (RSValues) {
  63414. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63415. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63416. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63417. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63418. }
  63419. else {
  63420. RSValues = { x: 0, y: 0 };
  63421. }
  63422. if (!camera.rotationQuaternion) {
  63423. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63424. }
  63425. else {
  63426. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63427. }
  63428. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63429. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63430. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63431. camera.cameraDirection.addInPlace(this._deltaTransform);
  63432. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63433. camera.cameraRotation.addInPlace(this._vector2);
  63434. }
  63435. };
  63436. FreeCameraGamepadInput.prototype.getClassName = function () {
  63437. return "FreeCameraGamepadInput";
  63438. };
  63439. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63440. return "gamepad";
  63441. };
  63442. __decorate([
  63443. BABYLON.serialize()
  63444. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63445. __decorate([
  63446. BABYLON.serialize()
  63447. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63448. return FreeCameraGamepadInput;
  63449. }());
  63450. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63451. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63452. })(BABYLON || (BABYLON = {}));
  63453. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63454. var BABYLON;
  63455. (function (BABYLON) {
  63456. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63457. function ArcRotateCameraGamepadInput() {
  63458. this.gamepadRotationSensibility = 80;
  63459. this.gamepadMoveSensibility = 40;
  63460. }
  63461. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63462. var _this = this;
  63463. var manager = this.camera.getScene().gamepadManager;
  63464. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63465. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63466. // prioritize XBOX gamepads.
  63467. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63468. _this.gamepad = gamepad;
  63469. }
  63470. }
  63471. });
  63472. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63473. if (_this.gamepad === gamepad) {
  63474. _this.gamepad = null;
  63475. }
  63476. });
  63477. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63478. };
  63479. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63480. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63481. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63482. this.gamepad = null;
  63483. };
  63484. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63485. if (this.gamepad) {
  63486. var camera = this.camera;
  63487. var RSValues = this.gamepad.rightStick;
  63488. if (RSValues) {
  63489. if (RSValues.x != 0) {
  63490. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63491. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63492. camera.inertialAlphaOffset += normalizedRX;
  63493. }
  63494. }
  63495. if (RSValues.y != 0) {
  63496. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63497. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63498. camera.inertialBetaOffset += normalizedRY;
  63499. }
  63500. }
  63501. }
  63502. var LSValues = this.gamepad.leftStick;
  63503. if (LSValues && LSValues.y != 0) {
  63504. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63505. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63506. this.camera.inertialRadiusOffset -= normalizedLY;
  63507. }
  63508. }
  63509. }
  63510. };
  63511. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63512. return "ArcRotateCameraGamepadInput";
  63513. };
  63514. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63515. return "gamepad";
  63516. };
  63517. __decorate([
  63518. BABYLON.serialize()
  63519. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63520. __decorate([
  63521. BABYLON.serialize()
  63522. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63523. return ArcRotateCameraGamepadInput;
  63524. }());
  63525. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63526. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63527. })(BABYLON || (BABYLON = {}));
  63528. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63529. var BABYLON;
  63530. (function (BABYLON) {
  63531. var GamepadManager = /** @class */ (function () {
  63532. function GamepadManager(_scene) {
  63533. var _this = this;
  63534. this._scene = _scene;
  63535. this._babylonGamepads = [];
  63536. this._oneGamepadConnected = false;
  63537. this._isMonitoring = false;
  63538. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63539. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63540. this._gamepadEventSupported = false;
  63541. }
  63542. else {
  63543. this._gamepadEventSupported = 'GamepadEvent' in window;
  63544. this._gamepadSupport = (navigator.getGamepads ||
  63545. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63546. }
  63547. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63548. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63549. for (var i in _this._babylonGamepads) {
  63550. var gamepad = _this._babylonGamepads[i];
  63551. if (gamepad && gamepad._isConnected) {
  63552. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63553. }
  63554. }
  63555. });
  63556. this._onGamepadConnectedEvent = function (evt) {
  63557. var gamepad = evt.gamepad;
  63558. if (gamepad.index in _this._babylonGamepads) {
  63559. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63560. return;
  63561. }
  63562. }
  63563. var newGamepad;
  63564. if (_this._babylonGamepads[gamepad.index]) {
  63565. newGamepad = _this._babylonGamepads[gamepad.index];
  63566. newGamepad.browserGamepad = gamepad;
  63567. newGamepad._isConnected = true;
  63568. }
  63569. else {
  63570. newGamepad = _this._addNewGamepad(gamepad);
  63571. }
  63572. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63573. _this._startMonitoringGamepads();
  63574. };
  63575. this._onGamepadDisconnectedEvent = function (evt) {
  63576. var gamepad = evt.gamepad;
  63577. // Remove the gamepad from the list of gamepads to monitor.
  63578. for (var i in _this._babylonGamepads) {
  63579. if (_this._babylonGamepads[i].index === gamepad.index) {
  63580. var disconnectedGamepad = _this._babylonGamepads[i];
  63581. disconnectedGamepad._isConnected = false;
  63582. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63583. break;
  63584. }
  63585. }
  63586. };
  63587. if (this._gamepadSupport) {
  63588. //first add already-connected gamepads
  63589. this._updateGamepadObjects();
  63590. if (this._babylonGamepads.length) {
  63591. this._startMonitoringGamepads();
  63592. }
  63593. // Checking if the gamepad connected event is supported (like in Firefox)
  63594. if (this._gamepadEventSupported) {
  63595. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63596. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63597. }
  63598. else {
  63599. this._startMonitoringGamepads();
  63600. }
  63601. }
  63602. }
  63603. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63604. get: function () {
  63605. return this._babylonGamepads;
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. GamepadManager.prototype.getGamepadByType = function (type) {
  63611. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63612. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63613. var gamepad = _a[_i];
  63614. if (gamepad && gamepad.type === type) {
  63615. return gamepad;
  63616. }
  63617. }
  63618. return null;
  63619. };
  63620. GamepadManager.prototype.dispose = function () {
  63621. if (this._gamepadEventSupported) {
  63622. if (this._onGamepadConnectedEvent) {
  63623. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63624. }
  63625. if (this._onGamepadDisconnectedEvent) {
  63626. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63627. }
  63628. this._onGamepadConnectedEvent = null;
  63629. this._onGamepadDisconnectedEvent = null;
  63630. }
  63631. this._babylonGamepads.forEach(function (gamepad) {
  63632. gamepad.dispose();
  63633. });
  63634. this.onGamepadConnectedObservable.clear();
  63635. this.onGamepadDisconnectedObservable.clear();
  63636. this._oneGamepadConnected = false;
  63637. this._stopMonitoringGamepads();
  63638. this._babylonGamepads = [];
  63639. };
  63640. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63641. if (!this._oneGamepadConnected) {
  63642. this._oneGamepadConnected = true;
  63643. }
  63644. var newGamepad;
  63645. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63646. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63647. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63648. }
  63649. else if (gamepad.pose) {
  63650. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63651. }
  63652. else {
  63653. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63654. }
  63655. this._babylonGamepads[newGamepad.index] = newGamepad;
  63656. return newGamepad;
  63657. };
  63658. GamepadManager.prototype._startMonitoringGamepads = function () {
  63659. if (!this._isMonitoring) {
  63660. this._isMonitoring = true;
  63661. //back-comp
  63662. if (!this._scene) {
  63663. this._checkGamepadsStatus();
  63664. }
  63665. }
  63666. };
  63667. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63668. this._isMonitoring = false;
  63669. };
  63670. GamepadManager.prototype._checkGamepadsStatus = function () {
  63671. var _this = this;
  63672. // Hack to be compatible Chrome
  63673. this._updateGamepadObjects();
  63674. for (var i in this._babylonGamepads) {
  63675. var gamepad = this._babylonGamepads[i];
  63676. if (!gamepad || !gamepad.isConnected) {
  63677. continue;
  63678. }
  63679. gamepad.update();
  63680. }
  63681. if (this._isMonitoring && !this._scene) {
  63682. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63683. }
  63684. };
  63685. // This function is called only on Chrome, which does not properly support
  63686. // connection/disconnection events and forces you to recopy again the gamepad object
  63687. GamepadManager.prototype._updateGamepadObjects = function () {
  63688. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63689. for (var i = 0; i < gamepads.length; i++) {
  63690. if (gamepads[i]) {
  63691. if (!this._babylonGamepads[gamepads[i].index]) {
  63692. var newGamepad = this._addNewGamepad(gamepads[i]);
  63693. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63694. }
  63695. else {
  63696. // Forced to copy again this object for Chrome for unknown reason
  63697. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63698. if (!this._babylonGamepads[i].isConnected) {
  63699. this._babylonGamepads[i]._isConnected = true;
  63700. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63701. }
  63702. }
  63703. }
  63704. }
  63705. };
  63706. return GamepadManager;
  63707. }());
  63708. BABYLON.GamepadManager = GamepadManager;
  63709. })(BABYLON || (BABYLON = {}));
  63710. //# sourceMappingURL=babylon.gamepadManager.js.map
  63711. var BABYLON;
  63712. (function (BABYLON) {
  63713. var StickValues = /** @class */ (function () {
  63714. function StickValues(x, y) {
  63715. this.x = x;
  63716. this.y = y;
  63717. }
  63718. return StickValues;
  63719. }());
  63720. BABYLON.StickValues = StickValues;
  63721. var Gamepad = /** @class */ (function () {
  63722. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63723. if (leftStickX === void 0) { leftStickX = 0; }
  63724. if (leftStickY === void 0) { leftStickY = 1; }
  63725. if (rightStickX === void 0) { rightStickX = 2; }
  63726. if (rightStickY === void 0) { rightStickY = 3; }
  63727. this.id = id;
  63728. this.index = index;
  63729. this.browserGamepad = browserGamepad;
  63730. this._isConnected = true;
  63731. this._invertLeftStickY = false;
  63732. this.type = Gamepad.GAMEPAD;
  63733. this._leftStickAxisX = leftStickX;
  63734. this._leftStickAxisY = leftStickY;
  63735. this._rightStickAxisX = rightStickX;
  63736. this._rightStickAxisY = rightStickY;
  63737. if (this.browserGamepad.axes.length >= 2) {
  63738. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63739. }
  63740. if (this.browserGamepad.axes.length >= 4) {
  63741. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63742. }
  63743. }
  63744. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63745. get: function () {
  63746. return this._isConnected;
  63747. },
  63748. enumerable: true,
  63749. configurable: true
  63750. });
  63751. Gamepad.prototype.onleftstickchanged = function (callback) {
  63752. this._onleftstickchanged = callback;
  63753. };
  63754. Gamepad.prototype.onrightstickchanged = function (callback) {
  63755. this._onrightstickchanged = callback;
  63756. };
  63757. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63758. get: function () {
  63759. return this._leftStick;
  63760. },
  63761. set: function (newValues) {
  63762. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63763. this._onleftstickchanged(newValues);
  63764. }
  63765. this._leftStick = newValues;
  63766. },
  63767. enumerable: true,
  63768. configurable: true
  63769. });
  63770. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63771. get: function () {
  63772. return this._rightStick;
  63773. },
  63774. set: function (newValues) {
  63775. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63776. this._onrightstickchanged(newValues);
  63777. }
  63778. this._rightStick = newValues;
  63779. },
  63780. enumerable: true,
  63781. configurable: true
  63782. });
  63783. Gamepad.prototype.update = function () {
  63784. if (this._leftStick) {
  63785. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63786. if (this._invertLeftStickY) {
  63787. this.leftStick.y *= -1;
  63788. }
  63789. }
  63790. if (this._rightStick) {
  63791. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63792. }
  63793. };
  63794. Gamepad.prototype.dispose = function () {
  63795. };
  63796. Gamepad.GAMEPAD = 0;
  63797. Gamepad.GENERIC = 1;
  63798. Gamepad.XBOX = 2;
  63799. Gamepad.POSE_ENABLED = 3;
  63800. return Gamepad;
  63801. }());
  63802. BABYLON.Gamepad = Gamepad;
  63803. var GenericPad = /** @class */ (function (_super) {
  63804. __extends(GenericPad, _super);
  63805. function GenericPad(id, index, browserGamepad) {
  63806. var _this = _super.call(this, id, index, browserGamepad) || this;
  63807. _this.onButtonDownObservable = new BABYLON.Observable();
  63808. _this.onButtonUpObservable = new BABYLON.Observable();
  63809. _this.type = Gamepad.GENERIC;
  63810. _this._buttons = new Array(browserGamepad.buttons.length);
  63811. return _this;
  63812. }
  63813. GenericPad.prototype.onbuttondown = function (callback) {
  63814. this._onbuttondown = callback;
  63815. };
  63816. GenericPad.prototype.onbuttonup = function (callback) {
  63817. this._onbuttonup = callback;
  63818. };
  63819. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63820. if (newValue !== currentValue) {
  63821. if (newValue === 1) {
  63822. if (this._onbuttondown) {
  63823. this._onbuttondown(buttonIndex);
  63824. }
  63825. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63826. }
  63827. if (newValue === 0) {
  63828. if (this._onbuttonup) {
  63829. this._onbuttonup(buttonIndex);
  63830. }
  63831. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63832. }
  63833. }
  63834. return newValue;
  63835. };
  63836. GenericPad.prototype.update = function () {
  63837. _super.prototype.update.call(this);
  63838. for (var index = 0; index < this._buttons.length; index++) {
  63839. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63840. }
  63841. };
  63842. GenericPad.prototype.dispose = function () {
  63843. _super.prototype.dispose.call(this);
  63844. this.onButtonDownObservable.clear();
  63845. this.onButtonUpObservable.clear();
  63846. };
  63847. return GenericPad;
  63848. }(Gamepad));
  63849. BABYLON.GenericPad = GenericPad;
  63850. })(BABYLON || (BABYLON = {}));
  63851. //# sourceMappingURL=babylon.gamepad.js.map
  63852. var BABYLON;
  63853. (function (BABYLON) {
  63854. var Xbox360Button;
  63855. (function (Xbox360Button) {
  63856. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63857. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63858. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63859. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63860. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63861. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63862. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63863. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63864. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63865. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63866. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63867. var Xbox360Dpad;
  63868. (function (Xbox360Dpad) {
  63869. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63870. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63871. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63872. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63873. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63874. var Xbox360Pad = /** @class */ (function (_super) {
  63875. __extends(Xbox360Pad, _super);
  63876. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63877. if (xboxOne === void 0) { xboxOne = false; }
  63878. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63879. _this._leftTrigger = 0;
  63880. _this._rightTrigger = 0;
  63881. _this.onButtonDownObservable = new BABYLON.Observable();
  63882. _this.onButtonUpObservable = new BABYLON.Observable();
  63883. _this.onPadDownObservable = new BABYLON.Observable();
  63884. _this.onPadUpObservable = new BABYLON.Observable();
  63885. _this._buttonA = 0;
  63886. _this._buttonB = 0;
  63887. _this._buttonX = 0;
  63888. _this._buttonY = 0;
  63889. _this._buttonBack = 0;
  63890. _this._buttonStart = 0;
  63891. _this._buttonLB = 0;
  63892. _this._buttonRB = 0;
  63893. _this._buttonLeftStick = 0;
  63894. _this._buttonRightStick = 0;
  63895. _this._dPadUp = 0;
  63896. _this._dPadDown = 0;
  63897. _this._dPadLeft = 0;
  63898. _this._dPadRight = 0;
  63899. _this._isXboxOnePad = false;
  63900. _this.type = BABYLON.Gamepad.XBOX;
  63901. _this._isXboxOnePad = xboxOne;
  63902. return _this;
  63903. }
  63904. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63905. this._onlefttriggerchanged = callback;
  63906. };
  63907. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63908. this._onrighttriggerchanged = callback;
  63909. };
  63910. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63911. get: function () {
  63912. return this._leftTrigger;
  63913. },
  63914. set: function (newValue) {
  63915. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63916. this._onlefttriggerchanged(newValue);
  63917. }
  63918. this._leftTrigger = newValue;
  63919. },
  63920. enumerable: true,
  63921. configurable: true
  63922. });
  63923. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63924. get: function () {
  63925. return this._rightTrigger;
  63926. },
  63927. set: function (newValue) {
  63928. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63929. this._onrighttriggerchanged(newValue);
  63930. }
  63931. this._rightTrigger = newValue;
  63932. },
  63933. enumerable: true,
  63934. configurable: true
  63935. });
  63936. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63937. this._onbuttondown = callback;
  63938. };
  63939. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63940. this._onbuttonup = callback;
  63941. };
  63942. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63943. this._ondpaddown = callback;
  63944. };
  63945. Xbox360Pad.prototype.ondpadup = function (callback) {
  63946. this._ondpadup = callback;
  63947. };
  63948. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63949. if (newValue !== currentValue) {
  63950. if (newValue === 1) {
  63951. if (this._onbuttondown) {
  63952. this._onbuttondown(buttonType);
  63953. }
  63954. this.onButtonDownObservable.notifyObservers(buttonType);
  63955. }
  63956. if (newValue === 0) {
  63957. if (this._onbuttonup) {
  63958. this._onbuttonup(buttonType);
  63959. }
  63960. this.onButtonUpObservable.notifyObservers(buttonType);
  63961. }
  63962. }
  63963. return newValue;
  63964. };
  63965. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63966. if (newValue !== currentValue) {
  63967. if (newValue === 1) {
  63968. if (this._ondpaddown) {
  63969. this._ondpaddown(buttonType);
  63970. }
  63971. this.onPadDownObservable.notifyObservers(buttonType);
  63972. }
  63973. if (newValue === 0) {
  63974. if (this._ondpadup) {
  63975. this._ondpadup(buttonType);
  63976. }
  63977. this.onPadUpObservable.notifyObservers(buttonType);
  63978. }
  63979. }
  63980. return newValue;
  63981. };
  63982. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63983. get: function () {
  63984. return this._buttonA;
  63985. },
  63986. set: function (value) {
  63987. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63988. },
  63989. enumerable: true,
  63990. configurable: true
  63991. });
  63992. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63993. get: function () {
  63994. return this._buttonB;
  63995. },
  63996. set: function (value) {
  63997. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63998. },
  63999. enumerable: true,
  64000. configurable: true
  64001. });
  64002. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64003. get: function () {
  64004. return this._buttonX;
  64005. },
  64006. set: function (value) {
  64007. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64008. },
  64009. enumerable: true,
  64010. configurable: true
  64011. });
  64012. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64013. get: function () {
  64014. return this._buttonY;
  64015. },
  64016. set: function (value) {
  64017. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64018. },
  64019. enumerable: true,
  64020. configurable: true
  64021. });
  64022. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64023. get: function () {
  64024. return this._buttonStart;
  64025. },
  64026. set: function (value) {
  64027. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64033. get: function () {
  64034. return this._buttonBack;
  64035. },
  64036. set: function (value) {
  64037. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64038. },
  64039. enumerable: true,
  64040. configurable: true
  64041. });
  64042. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64043. get: function () {
  64044. return this._buttonLB;
  64045. },
  64046. set: function (value) {
  64047. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64053. get: function () {
  64054. return this._buttonRB;
  64055. },
  64056. set: function (value) {
  64057. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64058. },
  64059. enumerable: true,
  64060. configurable: true
  64061. });
  64062. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64063. get: function () {
  64064. return this._buttonLeftStick;
  64065. },
  64066. set: function (value) {
  64067. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64068. },
  64069. enumerable: true,
  64070. configurable: true
  64071. });
  64072. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64073. get: function () {
  64074. return this._buttonRightStick;
  64075. },
  64076. set: function (value) {
  64077. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64078. },
  64079. enumerable: true,
  64080. configurable: true
  64081. });
  64082. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64083. get: function () {
  64084. return this._dPadUp;
  64085. },
  64086. set: function (value) {
  64087. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64088. },
  64089. enumerable: true,
  64090. configurable: true
  64091. });
  64092. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64093. get: function () {
  64094. return this._dPadDown;
  64095. },
  64096. set: function (value) {
  64097. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64098. },
  64099. enumerable: true,
  64100. configurable: true
  64101. });
  64102. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64103. get: function () {
  64104. return this._dPadLeft;
  64105. },
  64106. set: function (value) {
  64107. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64108. },
  64109. enumerable: true,
  64110. configurable: true
  64111. });
  64112. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64113. get: function () {
  64114. return this._dPadRight;
  64115. },
  64116. set: function (value) {
  64117. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64118. },
  64119. enumerable: true,
  64120. configurable: true
  64121. });
  64122. Xbox360Pad.prototype.update = function () {
  64123. _super.prototype.update.call(this);
  64124. if (this._isXboxOnePad) {
  64125. this.buttonA = this.browserGamepad.buttons[0].value;
  64126. this.buttonB = this.browserGamepad.buttons[1].value;
  64127. this.buttonX = this.browserGamepad.buttons[2].value;
  64128. this.buttonY = this.browserGamepad.buttons[3].value;
  64129. this.buttonLB = this.browserGamepad.buttons[4].value;
  64130. this.buttonRB = this.browserGamepad.buttons[5].value;
  64131. this.leftTrigger = this.browserGamepad.axes[2];
  64132. this.rightTrigger = this.browserGamepad.axes[5];
  64133. this.buttonBack = this.browserGamepad.buttons[9].value;
  64134. this.buttonStart = this.browserGamepad.buttons[8].value;
  64135. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64136. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64137. this.dPadUp = this.browserGamepad.buttons[11].value;
  64138. this.dPadDown = this.browserGamepad.buttons[12].value;
  64139. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64140. this.dPadRight = this.browserGamepad.buttons[14].value;
  64141. }
  64142. else {
  64143. this.buttonA = this.browserGamepad.buttons[0].value;
  64144. this.buttonB = this.browserGamepad.buttons[1].value;
  64145. this.buttonX = this.browserGamepad.buttons[2].value;
  64146. this.buttonY = this.browserGamepad.buttons[3].value;
  64147. this.buttonLB = this.browserGamepad.buttons[4].value;
  64148. this.buttonRB = this.browserGamepad.buttons[5].value;
  64149. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64150. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64151. this.buttonBack = this.browserGamepad.buttons[8].value;
  64152. this.buttonStart = this.browserGamepad.buttons[9].value;
  64153. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64154. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64155. this.dPadUp = this.browserGamepad.buttons[12].value;
  64156. this.dPadDown = this.browserGamepad.buttons[13].value;
  64157. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64158. this.dPadRight = this.browserGamepad.buttons[15].value;
  64159. }
  64160. };
  64161. Xbox360Pad.prototype.dispose = function () {
  64162. _super.prototype.dispose.call(this);
  64163. this.onButtonDownObservable.clear();
  64164. this.onButtonUpObservable.clear();
  64165. this.onPadDownObservable.clear();
  64166. this.onPadUpObservable.clear();
  64167. };
  64168. return Xbox360Pad;
  64169. }(BABYLON.Gamepad));
  64170. BABYLON.Xbox360Pad = Xbox360Pad;
  64171. })(BABYLON || (BABYLON = {}));
  64172. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64173. var BABYLON;
  64174. (function (BABYLON) {
  64175. var PoseEnabledControllerType;
  64176. (function (PoseEnabledControllerType) {
  64177. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64178. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64179. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64180. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64181. /**
  64182. * Google Daydream
  64183. */
  64184. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64185. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64186. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64187. var PoseEnabledControllerHelper = /** @class */ (function () {
  64188. function PoseEnabledControllerHelper() {
  64189. }
  64190. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64191. // Oculus Touch
  64192. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64193. return new BABYLON.OculusTouchController(vrGamepad);
  64194. }
  64195. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64196. return new BABYLON.WindowsMotionController(vrGamepad);
  64197. }
  64198. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64199. return new BABYLON.ViveController(vrGamepad);
  64200. }
  64201. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64202. return new BABYLON.GearVRController(vrGamepad);
  64203. }
  64204. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64205. return new BABYLON.DaydreamController(vrGamepad);
  64206. }
  64207. else {
  64208. return new BABYLON.GenericController(vrGamepad);
  64209. }
  64210. };
  64211. return PoseEnabledControllerHelper;
  64212. }());
  64213. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64214. var PoseEnabledController = /** @class */ (function (_super) {
  64215. __extends(PoseEnabledController, _super);
  64216. function PoseEnabledController(browserGamepad) {
  64217. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64218. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64219. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64220. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64221. // Represents device position and rotation in babylon space
  64222. _this.devicePosition = BABYLON.Vector3.Zero();
  64223. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64224. _this.deviceScaleFactor = 1;
  64225. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64226. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64227. _this._workingMatrix = BABYLON.Matrix.Identity();
  64228. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64229. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64230. _this.position = BABYLON.Vector3.Zero();
  64231. _this.rotationQuaternion = new BABYLON.Quaternion();
  64232. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64233. _this._calculatedRotation = new BABYLON.Quaternion();
  64234. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64235. return _this;
  64236. }
  64237. PoseEnabledController.prototype.update = function () {
  64238. _super.prototype.update.call(this);
  64239. var pose = this.browserGamepad.pose;
  64240. this.updateFromDevice(pose);
  64241. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64242. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64243. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64244. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64245. if (this._mesh) {
  64246. this._mesh.position.copyFrom(this.devicePosition);
  64247. if (this._mesh.rotationQuaternion) {
  64248. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64249. }
  64250. }
  64251. };
  64252. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64253. if (poseData) {
  64254. this.rawPose = poseData;
  64255. if (poseData.position) {
  64256. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64257. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64258. this._deviceRoomPosition.z *= -1;
  64259. }
  64260. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64261. this._calculatedPosition.addInPlace(this.position);
  64262. }
  64263. var pose = this.rawPose;
  64264. if (poseData.orientation && pose.orientation) {
  64265. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64266. if (this._mesh) {
  64267. if (this._mesh.getScene().useRightHandedSystem) {
  64268. this._deviceRoomRotationQuaternion.z *= -1;
  64269. this._deviceRoomRotationQuaternion.w *= -1;
  64270. }
  64271. else {
  64272. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64273. }
  64274. }
  64275. // if the camera is set, rotate to the camera's rotation
  64276. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64277. }
  64278. }
  64279. };
  64280. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64281. if (this._mesh) {
  64282. this._mesh.parent = null;
  64283. }
  64284. this._mesh = mesh;
  64285. if (this._poseControlledCamera) {
  64286. this._mesh.parent = this._poseControlledCamera;
  64287. }
  64288. if (!this._mesh.rotationQuaternion) {
  64289. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64290. }
  64291. };
  64292. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64293. this._poseControlledCamera = camera;
  64294. if (this._mesh) {
  64295. this._mesh.parent = this._poseControlledCamera;
  64296. }
  64297. };
  64298. PoseEnabledController.prototype.dispose = function () {
  64299. if (this._mesh) {
  64300. this._mesh.dispose();
  64301. }
  64302. this._mesh = null;
  64303. _super.prototype.dispose.call(this);
  64304. };
  64305. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64306. get: function () {
  64307. return this._mesh;
  64308. },
  64309. enumerable: true,
  64310. configurable: true
  64311. });
  64312. PoseEnabledController.prototype.getForwardRay = function (length) {
  64313. if (length === void 0) { length = 100; }
  64314. if (!this.mesh) {
  64315. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64316. }
  64317. var m = this.mesh.getWorldMatrix();
  64318. var origin = m.getTranslation();
  64319. var forward = new BABYLON.Vector3(0, 0, -1);
  64320. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64321. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64322. return new BABYLON.Ray(origin, direction, length);
  64323. };
  64324. return PoseEnabledController;
  64325. }(BABYLON.Gamepad));
  64326. BABYLON.PoseEnabledController = PoseEnabledController;
  64327. })(BABYLON || (BABYLON = {}));
  64328. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64329. var BABYLON;
  64330. (function (BABYLON) {
  64331. var WebVRController = /** @class */ (function (_super) {
  64332. __extends(WebVRController, _super);
  64333. function WebVRController(vrGamepad) {
  64334. var _this = _super.call(this, vrGamepad) || this;
  64335. // Observables
  64336. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64337. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64338. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64339. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64340. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64341. _this.pad = { x: 0, y: 0 };
  64342. // avoid GC, store state in a tmp object
  64343. _this._changes = {
  64344. pressChanged: false,
  64345. touchChanged: false,
  64346. valueChanged: false,
  64347. changed: false
  64348. };
  64349. _this._buttons = new Array(vrGamepad.buttons.length);
  64350. _this.hand = vrGamepad.hand;
  64351. return _this;
  64352. }
  64353. WebVRController.prototype.onButtonStateChange = function (callback) {
  64354. this._onButtonStateChange = callback;
  64355. };
  64356. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64357. get: function () {
  64358. return this._defaultModel;
  64359. },
  64360. enumerable: true,
  64361. configurable: true
  64362. });
  64363. WebVRController.prototype.update = function () {
  64364. _super.prototype.update.call(this);
  64365. for (var index = 0; index < this._buttons.length; index++) {
  64366. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64367. }
  64368. ;
  64369. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64370. this.pad.x = this.leftStick.x;
  64371. this.pad.y = this.leftStick.y;
  64372. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64373. }
  64374. };
  64375. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64376. if (!newState) {
  64377. newState = {
  64378. pressed: false,
  64379. touched: false,
  64380. value: 0
  64381. };
  64382. }
  64383. if (!currentState) {
  64384. this._buttons[buttonIndex] = {
  64385. pressed: newState.pressed,
  64386. touched: newState.touched,
  64387. value: newState.value
  64388. };
  64389. return;
  64390. }
  64391. this._checkChanges(newState, currentState);
  64392. if (this._changes.changed) {
  64393. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64394. this._handleButtonChange(buttonIndex, newState, this._changes);
  64395. }
  64396. this._buttons[buttonIndex].pressed = newState.pressed;
  64397. this._buttons[buttonIndex].touched = newState.touched;
  64398. // oculus triggers are never 0, thou not touched.
  64399. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64400. };
  64401. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64402. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64403. this._changes.touchChanged = newState.touched !== currentState.touched;
  64404. this._changes.valueChanged = newState.value !== currentState.value;
  64405. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64406. return this._changes;
  64407. };
  64408. WebVRController.prototype.dispose = function () {
  64409. _super.prototype.dispose.call(this);
  64410. this.onTriggerStateChangedObservable.clear();
  64411. this.onMainButtonStateChangedObservable.clear();
  64412. this.onSecondaryButtonStateChangedObservable.clear();
  64413. this.onPadStateChangedObservable.clear();
  64414. this.onPadValuesChangedObservable.clear();
  64415. };
  64416. return WebVRController;
  64417. }(BABYLON.PoseEnabledController));
  64418. BABYLON.WebVRController = WebVRController;
  64419. })(BABYLON || (BABYLON = {}));
  64420. //# sourceMappingURL=babylon.webVRController.js.map
  64421. var BABYLON;
  64422. (function (BABYLON) {
  64423. var OculusTouchController = /** @class */ (function (_super) {
  64424. __extends(OculusTouchController, _super);
  64425. function OculusTouchController(vrGamepad) {
  64426. var _this = _super.call(this, vrGamepad) || this;
  64427. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64428. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64429. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64430. return _this;
  64431. }
  64432. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64433. var _this = this;
  64434. var meshName;
  64435. // Hand
  64436. if (this.hand === 'left') {
  64437. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64438. }
  64439. else {
  64440. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64441. }
  64442. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64443. /*
  64444. Parent Mesh name: oculus_touch_left
  64445. - body
  64446. - trigger
  64447. - thumbstick
  64448. - grip
  64449. - button_y
  64450. - button_x
  64451. - button_enter
  64452. */
  64453. _this._defaultModel = newMeshes[1];
  64454. _this.attachToMesh(_this._defaultModel);
  64455. if (meshLoaded) {
  64456. meshLoaded(_this._defaultModel);
  64457. }
  64458. });
  64459. };
  64460. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64461. // helper getters for left and right hand.
  64462. get: function () {
  64463. if (this.hand === 'right') {
  64464. return this.onMainButtonStateChangedObservable;
  64465. }
  64466. else {
  64467. throw new Error('No A button on left hand');
  64468. }
  64469. },
  64470. enumerable: true,
  64471. configurable: true
  64472. });
  64473. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64474. get: function () {
  64475. if (this.hand === 'right') {
  64476. return this.onSecondaryButtonStateChangedObservable;
  64477. }
  64478. else {
  64479. throw new Error('No B button on left hand');
  64480. }
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64486. get: function () {
  64487. if (this.hand === 'left') {
  64488. return this.onMainButtonStateChangedObservable;
  64489. }
  64490. else {
  64491. throw new Error('No X button on right hand');
  64492. }
  64493. },
  64494. enumerable: true,
  64495. configurable: true
  64496. });
  64497. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64498. get: function () {
  64499. if (this.hand === 'left') {
  64500. return this.onSecondaryButtonStateChangedObservable;
  64501. }
  64502. else {
  64503. throw new Error('No Y button on right hand');
  64504. }
  64505. },
  64506. enumerable: true,
  64507. configurable: true
  64508. });
  64509. /*
  64510. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64511. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64512. 2) secondary trigger (same)
  64513. 3) A (right) X (left), touch, pressed = value
  64514. 4) B / Y
  64515. 5) thumb rest
  64516. */
  64517. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64518. var notifyObject = state; //{ state: state, changes: changes };
  64519. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64520. switch (buttonIdx) {
  64521. case 0:
  64522. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64523. return;
  64524. case 1:// index trigger
  64525. if (this._defaultModel) {
  64526. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64527. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64528. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64529. }
  64530. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64531. return;
  64532. case 2:// secondary trigger
  64533. if (this._defaultModel) {
  64534. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64535. }
  64536. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64537. return;
  64538. case 3:
  64539. if (this._defaultModel) {
  64540. if (notifyObject.pressed) {
  64541. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64542. }
  64543. else {
  64544. (this._defaultModel.getChildren()[1]).position.y = 0;
  64545. }
  64546. }
  64547. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64548. return;
  64549. case 4:
  64550. if (this._defaultModel) {
  64551. if (notifyObject.pressed) {
  64552. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64553. }
  64554. else {
  64555. (this._defaultModel.getChildren()[2]).position.y = 0;
  64556. }
  64557. }
  64558. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64559. return;
  64560. case 5:
  64561. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64562. return;
  64563. }
  64564. };
  64565. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64566. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64567. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64568. return OculusTouchController;
  64569. }(BABYLON.WebVRController));
  64570. BABYLON.OculusTouchController = OculusTouchController;
  64571. })(BABYLON || (BABYLON = {}));
  64572. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64573. var BABYLON;
  64574. (function (BABYLON) {
  64575. var ViveController = /** @class */ (function (_super) {
  64576. __extends(ViveController, _super);
  64577. function ViveController(vrGamepad) {
  64578. var _this = _super.call(this, vrGamepad) || this;
  64579. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64580. _this._invertLeftStickY = true;
  64581. return _this;
  64582. }
  64583. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64584. var _this = this;
  64585. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64586. /*
  64587. Parent Mesh name: ViveWand
  64588. - body
  64589. - r_gripper
  64590. - l_gripper
  64591. - menu_button
  64592. - system_button
  64593. - trackpad
  64594. - trigger
  64595. - LED
  64596. */
  64597. _this._defaultModel = newMeshes[1];
  64598. _this.attachToMesh(_this._defaultModel);
  64599. if (meshLoaded) {
  64600. meshLoaded(_this._defaultModel);
  64601. }
  64602. });
  64603. };
  64604. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64605. get: function () {
  64606. return this.onMainButtonStateChangedObservable;
  64607. },
  64608. enumerable: true,
  64609. configurable: true
  64610. });
  64611. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64612. get: function () {
  64613. return this.onMainButtonStateChangedObservable;
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64619. get: function () {
  64620. return this.onSecondaryButtonStateChangedObservable;
  64621. },
  64622. enumerable: true,
  64623. configurable: true
  64624. });
  64625. /**
  64626. * Vive mapping:
  64627. * 0: touchpad
  64628. * 1: trigger
  64629. * 2: left AND right buttons
  64630. * 3: menu button
  64631. */
  64632. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64633. var notifyObject = state; //{ state: state, changes: changes };
  64634. switch (buttonIdx) {
  64635. case 0:
  64636. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64637. return;
  64638. case 1:// index trigger
  64639. if (this._defaultModel) {
  64640. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64641. }
  64642. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64643. return;
  64644. case 2:// left AND right button
  64645. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64646. return;
  64647. case 3:
  64648. if (this._defaultModel) {
  64649. if (notifyObject.pressed) {
  64650. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64651. }
  64652. else {
  64653. (this._defaultModel.getChildren()[2]).position.y = 0;
  64654. }
  64655. }
  64656. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64657. return;
  64658. }
  64659. };
  64660. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64661. ViveController.MODEL_FILENAME = 'wand.babylon';
  64662. return ViveController;
  64663. }(BABYLON.WebVRController));
  64664. BABYLON.ViveController = ViveController;
  64665. })(BABYLON || (BABYLON = {}));
  64666. //# sourceMappingURL=babylon.viveController.js.map
  64667. var BABYLON;
  64668. (function (BABYLON) {
  64669. var GenericController = /** @class */ (function (_super) {
  64670. __extends(GenericController, _super);
  64671. function GenericController(vrGamepad) {
  64672. return _super.call(this, vrGamepad) || this;
  64673. }
  64674. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64675. var _this = this;
  64676. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64677. _this._defaultModel = newMeshes[1];
  64678. _this.attachToMesh(_this._defaultModel);
  64679. if (meshLoaded) {
  64680. meshLoaded(_this._defaultModel);
  64681. }
  64682. });
  64683. };
  64684. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64685. console.log("Button id: " + buttonIdx + "state: ");
  64686. console.dir(state);
  64687. };
  64688. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64689. GenericController.MODEL_FILENAME = 'generic.babylon';
  64690. return GenericController;
  64691. }(BABYLON.WebVRController));
  64692. BABYLON.GenericController = GenericController;
  64693. })(BABYLON || (BABYLON = {}));
  64694. //# sourceMappingURL=babylon.genericController.js.map
  64695. var BABYLON;
  64696. (function (BABYLON) {
  64697. var LoadedMeshInfo = /** @class */ (function () {
  64698. function LoadedMeshInfo() {
  64699. this.buttonMeshes = {};
  64700. this.axisMeshes = {};
  64701. }
  64702. return LoadedMeshInfo;
  64703. }());
  64704. var WindowsMotionController = /** @class */ (function (_super) {
  64705. __extends(WindowsMotionController, _super);
  64706. function WindowsMotionController(vrGamepad) {
  64707. var _this = _super.call(this, vrGamepad) || this;
  64708. _this._mapping = {
  64709. // Semantic button names
  64710. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64711. // A mapping of the button name to glTF model node name
  64712. // that should be transformed by button value.
  64713. buttonMeshNames: {
  64714. 'trigger': 'SELECT',
  64715. 'menu': 'MENU',
  64716. 'grip': 'GRASP',
  64717. 'thumbstick': 'THUMBSTICK_PRESS',
  64718. 'trackpad': 'TOUCHPAD_PRESS'
  64719. },
  64720. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64721. buttonObservableNames: {
  64722. 'trigger': 'onTriggerStateChangedObservable',
  64723. 'menu': 'onSecondaryButtonStateChangedObservable',
  64724. 'grip': 'onMainButtonStateChangedObservable',
  64725. 'thumbstick': 'onPadStateChangedObservable',
  64726. 'trackpad': 'onTrackpadChangedObservable'
  64727. },
  64728. // A mapping of the axis name to glTF model node name
  64729. // that should be transformed by axis value.
  64730. // This array mirrors the browserGamepad.axes array, such that
  64731. // the mesh corresponding to axis 0 is in this array index 0.
  64732. axisMeshNames: [
  64733. 'THUMBSTICK_X',
  64734. 'THUMBSTICK_Y',
  64735. 'TOUCHPAD_TOUCH_X',
  64736. 'TOUCHPAD_TOUCH_Y'
  64737. ],
  64738. pointingPoseMeshName: 'POINTING_POSE'
  64739. };
  64740. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64741. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64742. _this.trackpad = { x: 0, y: 0 };
  64743. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64744. _this._loadedMeshInfo = null;
  64745. return _this;
  64746. }
  64747. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64748. get: function () {
  64749. return this.onTriggerStateChangedObservable;
  64750. },
  64751. enumerable: true,
  64752. configurable: true
  64753. });
  64754. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64755. get: function () {
  64756. return this.onSecondaryButtonStateChangedObservable;
  64757. },
  64758. enumerable: true,
  64759. configurable: true
  64760. });
  64761. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64762. get: function () {
  64763. return this.onMainButtonStateChangedObservable;
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64769. get: function () {
  64770. return this.onPadStateChangedObservable;
  64771. },
  64772. enumerable: true,
  64773. configurable: true
  64774. });
  64775. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64776. get: function () {
  64777. return this.onTrackpadChangedObservable;
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64783. get: function () {
  64784. return this.onTrackpadValuesChangedObservable;
  64785. },
  64786. enumerable: true,
  64787. configurable: true
  64788. });
  64789. /**
  64790. * Called once per frame by the engine.
  64791. */
  64792. WindowsMotionController.prototype.update = function () {
  64793. _super.prototype.update.call(this);
  64794. // Only need to animate axes if there is a loaded mesh
  64795. if (this._loadedMeshInfo) {
  64796. if (this.browserGamepad.axes) {
  64797. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64798. this.trackpad.x = this.browserGamepad["axes"][2];
  64799. this.trackpad.y = this.browserGamepad["axes"][3];
  64800. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64801. }
  64802. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64803. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64804. }
  64805. }
  64806. }
  64807. };
  64808. /**
  64809. * Called once for each button that changed state since the last frame
  64810. * @param buttonIdx Which button index changed
  64811. * @param state New state of the button
  64812. * @param changes Which properties on the state changed since last frame
  64813. */
  64814. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64815. var buttonName = this._mapping.buttons[buttonIdx];
  64816. if (!buttonName) {
  64817. return;
  64818. }
  64819. // Only emit events for buttons that we know how to map from index to name
  64820. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64821. if (observable) {
  64822. observable.notifyObservers(state);
  64823. }
  64824. this.lerpButtonTransform(buttonName, state.value);
  64825. };
  64826. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64827. // If there is no loaded mesh, there is nothing to transform.
  64828. if (!this._loadedMeshInfo) {
  64829. return;
  64830. }
  64831. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64832. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64833. return;
  64834. }
  64835. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64836. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64837. };
  64838. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64839. if (!this._loadedMeshInfo) {
  64840. return;
  64841. }
  64842. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64843. if (!meshInfo) {
  64844. return;
  64845. }
  64846. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64847. return;
  64848. }
  64849. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64850. var lerpValue = axisValue * 0.5 + 0.5;
  64851. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64852. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64853. };
  64854. /**
  64855. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64856. * @param scene scene in which to add meshes
  64857. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64858. */
  64859. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64860. var _this = this;
  64861. if (forceDefault === void 0) { forceDefault = false; }
  64862. var path;
  64863. var filename;
  64864. // Checking if GLB loader is present
  64865. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64866. // Determine the device specific folder based on the ID suffix
  64867. var device = 'default';
  64868. if (this.id && !forceDefault) {
  64869. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64870. device = ((match && match[0]) || device);
  64871. }
  64872. // Hand
  64873. if (this.hand === 'left') {
  64874. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64875. }
  64876. else {
  64877. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64878. }
  64879. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64880. }
  64881. else {
  64882. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64883. path = BABYLON.GenericController.MODEL_BASE_URL;
  64884. filename = BABYLON.GenericController.MODEL_FILENAME;
  64885. }
  64886. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64887. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64888. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64889. if (!_this._loadedMeshInfo) {
  64890. return;
  64891. }
  64892. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64893. _this.attachToMesh(_this._defaultModel);
  64894. if (meshLoaded) {
  64895. meshLoaded(_this._defaultModel);
  64896. }
  64897. }, null, function (scene, message) {
  64898. BABYLON.Tools.Log(message);
  64899. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64900. if (!forceDefault) {
  64901. _this.initControllerMesh(scene, meshLoaded, true);
  64902. }
  64903. });
  64904. };
  64905. /**
  64906. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64907. * can be transformed by button presses and axes values, based on this._mapping.
  64908. *
  64909. * @param scene scene in which the meshes exist
  64910. * @param meshes list of meshes that make up the controller model to process
  64911. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64912. */
  64913. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64914. var loadedMeshInfo = null;
  64915. // Create a new mesh to contain the glTF hierarchy
  64916. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64917. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64918. var childMesh = null;
  64919. for (var i = 0; i < meshes.length; i++) {
  64920. var mesh = meshes[i];
  64921. if (!mesh.parent) {
  64922. // Exclude controller meshes from picking results
  64923. mesh.isPickable = false;
  64924. // Handle root node, attach to the new parentMesh
  64925. childMesh = mesh;
  64926. break;
  64927. }
  64928. }
  64929. if (childMesh) {
  64930. childMesh.setParent(parentMesh);
  64931. // Create our mesh info. Note that this method will always return non-null.
  64932. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64933. }
  64934. else {
  64935. BABYLON.Tools.Warn('Could not find root node in model file.');
  64936. }
  64937. return loadedMeshInfo;
  64938. };
  64939. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64940. var loadedMeshInfo = new LoadedMeshInfo();
  64941. var i;
  64942. loadedMeshInfo.rootNode = rootNode;
  64943. // Reset the caches
  64944. loadedMeshInfo.buttonMeshes = {};
  64945. loadedMeshInfo.axisMeshes = {};
  64946. // Button Meshes
  64947. for (i = 0; i < this._mapping.buttons.length; i++) {
  64948. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64949. if (!buttonMeshName) {
  64950. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64951. continue;
  64952. }
  64953. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64954. if (!buttonMesh) {
  64955. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64956. continue;
  64957. }
  64958. var buttonMeshInfo = {
  64959. index: i,
  64960. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64961. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64962. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64963. };
  64964. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64965. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64966. }
  64967. else {
  64968. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64969. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64970. '(VALUE: ' + !!buttonMeshInfo.value +
  64971. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64972. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64973. ')');
  64974. }
  64975. }
  64976. // Axis Meshes
  64977. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64978. var axisMeshName = this._mapping.axisMeshNames[i];
  64979. if (!axisMeshName) {
  64980. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64981. continue;
  64982. }
  64983. var axisMesh = getChildByName(rootNode, axisMeshName);
  64984. if (!axisMesh) {
  64985. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64986. continue;
  64987. }
  64988. var axisMeshInfo = {
  64989. index: i,
  64990. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64991. min: getImmediateChildByName(axisMesh, 'MIN'),
  64992. max: getImmediateChildByName(axisMesh, 'MAX')
  64993. };
  64994. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64995. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64996. }
  64997. else {
  64998. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64999. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65000. '(VALUE: ' + !!axisMeshInfo.value +
  65001. ', MIN: ' + !!axisMeshInfo.min +
  65002. ', MAX:' + !!axisMeshInfo.max +
  65003. ')');
  65004. }
  65005. }
  65006. // Pointing Ray
  65007. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65008. if (!loadedMeshInfo.pointingPoseNode) {
  65009. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65010. }
  65011. return loadedMeshInfo;
  65012. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65013. function getChildByName(node, name) {
  65014. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65015. }
  65016. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65017. function getImmediateChildByName(node, name) {
  65018. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65019. }
  65020. };
  65021. WindowsMotionController.prototype.getForwardRay = function (length) {
  65022. if (length === void 0) { length = 100; }
  65023. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65024. return _super.prototype.getForwardRay.call(this, length);
  65025. }
  65026. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65027. var origin = m.getTranslation();
  65028. var forward = new BABYLON.Vector3(0, 0, -1);
  65029. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65030. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65031. return new BABYLON.Ray(origin, direction, length);
  65032. };
  65033. WindowsMotionController.prototype.dispose = function () {
  65034. _super.prototype.dispose.call(this);
  65035. this.onTrackpadChangedObservable.clear();
  65036. };
  65037. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65038. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65039. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65040. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65041. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65042. return WindowsMotionController;
  65043. }(BABYLON.WebVRController));
  65044. BABYLON.WindowsMotionController = WindowsMotionController;
  65045. })(BABYLON || (BABYLON = {}));
  65046. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65047. var BABYLON;
  65048. (function (BABYLON) {
  65049. var GearVRController = /** @class */ (function (_super) {
  65050. __extends(GearVRController, _super);
  65051. function GearVRController(vrGamepad) {
  65052. var _this = _super.call(this, vrGamepad) || this;
  65053. _this._buttonIndexToObservableNameMap = [
  65054. 'onTrackpadChangedObservable',
  65055. 'onTriggerStateChangedObservable' // Trigger
  65056. ];
  65057. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65058. return _this;
  65059. }
  65060. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65061. var _this = this;
  65062. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65063. _this._defaultModel = newMeshes[1];
  65064. _this.attachToMesh(_this._defaultModel);
  65065. if (meshLoaded) {
  65066. meshLoaded(_this._defaultModel);
  65067. }
  65068. });
  65069. };
  65070. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65071. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65072. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65073. // Only emit events for buttons that we know how to map from index to observable
  65074. var observable = this[observableName];
  65075. if (observable) {
  65076. observable.notifyObservers(state);
  65077. }
  65078. }
  65079. };
  65080. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65081. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65082. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65083. return GearVRController;
  65084. }(BABYLON.WebVRController));
  65085. BABYLON.GearVRController = GearVRController;
  65086. })(BABYLON || (BABYLON = {}));
  65087. //# sourceMappingURL=babylon.gearVRController.js.map
  65088. var BABYLON;
  65089. (function (BABYLON) {
  65090. /**
  65091. * Google Daydream controller
  65092. */
  65093. var DaydreamController = /** @class */ (function (_super) {
  65094. __extends(DaydreamController, _super);
  65095. function DaydreamController(vrGamepad) {
  65096. var _this = _super.call(this, vrGamepad) || this;
  65097. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65098. return _this;
  65099. }
  65100. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65101. var _this = this;
  65102. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65103. _this._defaultModel = newMeshes[1];
  65104. _this.attachToMesh(_this._defaultModel);
  65105. if (meshLoaded) {
  65106. meshLoaded(_this._defaultModel);
  65107. }
  65108. });
  65109. };
  65110. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65111. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65112. if (buttonIdx === 0) {
  65113. var observable = this.onTriggerStateChangedObservable;
  65114. if (observable) {
  65115. observable.notifyObservers(state);
  65116. }
  65117. }
  65118. else {
  65119. // If the app or home buttons are ever made available
  65120. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65121. }
  65122. };
  65123. /**
  65124. * Base Url for the controller model.
  65125. */
  65126. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65127. /**
  65128. * File name for the controller model.
  65129. */
  65130. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65131. /**
  65132. * Gamepad Id prefix used to identify Daydream Controller.
  65133. */
  65134. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65135. return DaydreamController;
  65136. }(BABYLON.WebVRController));
  65137. BABYLON.DaydreamController = DaydreamController;
  65138. })(BABYLON || (BABYLON = {}));
  65139. //# sourceMappingURL=babylon.daydreamController.js.map
  65140. var BABYLON;
  65141. (function (BABYLON) {
  65142. var FollowCamera = /** @class */ (function (_super) {
  65143. __extends(FollowCamera, _super);
  65144. function FollowCamera(name, position, scene, lockedTarget) {
  65145. if (lockedTarget === void 0) { lockedTarget = null; }
  65146. var _this = _super.call(this, name, position, scene) || this;
  65147. _this.radius = 12;
  65148. _this.rotationOffset = 0;
  65149. _this.heightOffset = 4;
  65150. _this.cameraAcceleration = 0.05;
  65151. _this.maxCameraSpeed = 20;
  65152. _this.lockedTarget = lockedTarget;
  65153. return _this;
  65154. }
  65155. FollowCamera.prototype.getRadians = function (degrees) {
  65156. return degrees * Math.PI / 180;
  65157. };
  65158. FollowCamera.prototype.follow = function (cameraTarget) {
  65159. if (!cameraTarget)
  65160. return;
  65161. var yRotation;
  65162. if (cameraTarget.rotationQuaternion) {
  65163. var rotMatrix = new BABYLON.Matrix();
  65164. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65165. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65166. }
  65167. else {
  65168. yRotation = cameraTarget.rotation.y;
  65169. }
  65170. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65171. var targetPosition = cameraTarget.getAbsolutePosition();
  65172. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65173. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65174. var dx = targetX - this.position.x;
  65175. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65176. var dz = (targetZ) - this.position.z;
  65177. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65178. var vy = dy * this.cameraAcceleration;
  65179. var vz = dz * this.cameraAcceleration * 2;
  65180. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65181. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65182. }
  65183. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65184. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65185. }
  65186. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65187. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65188. }
  65189. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65190. this.setTarget(targetPosition);
  65191. };
  65192. FollowCamera.prototype._checkInputs = function () {
  65193. _super.prototype._checkInputs.call(this);
  65194. if (this.lockedTarget) {
  65195. this.follow(this.lockedTarget);
  65196. }
  65197. };
  65198. FollowCamera.prototype.getClassName = function () {
  65199. return "FollowCamera";
  65200. };
  65201. __decorate([
  65202. BABYLON.serialize()
  65203. ], FollowCamera.prototype, "radius", void 0);
  65204. __decorate([
  65205. BABYLON.serialize()
  65206. ], FollowCamera.prototype, "rotationOffset", void 0);
  65207. __decorate([
  65208. BABYLON.serialize()
  65209. ], FollowCamera.prototype, "heightOffset", void 0);
  65210. __decorate([
  65211. BABYLON.serialize()
  65212. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65213. __decorate([
  65214. BABYLON.serialize()
  65215. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65216. __decorate([
  65217. BABYLON.serializeAsMeshReference("lockedTargetId")
  65218. ], FollowCamera.prototype, "lockedTarget", void 0);
  65219. return FollowCamera;
  65220. }(BABYLON.TargetCamera));
  65221. BABYLON.FollowCamera = FollowCamera;
  65222. var ArcFollowCamera = /** @class */ (function (_super) {
  65223. __extends(ArcFollowCamera, _super);
  65224. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65225. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65226. _this.alpha = alpha;
  65227. _this.beta = beta;
  65228. _this.radius = radius;
  65229. _this.target = target;
  65230. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65231. _this.follow();
  65232. return _this;
  65233. }
  65234. ArcFollowCamera.prototype.follow = function () {
  65235. if (!this.target) {
  65236. return;
  65237. }
  65238. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65239. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65240. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65241. var targetPosition = this.target.getAbsolutePosition();
  65242. this.position = targetPosition.add(this._cartesianCoordinates);
  65243. this.setTarget(targetPosition);
  65244. };
  65245. ArcFollowCamera.prototype._checkInputs = function () {
  65246. _super.prototype._checkInputs.call(this);
  65247. this.follow();
  65248. };
  65249. ArcFollowCamera.prototype.getClassName = function () {
  65250. return "ArcFollowCamera";
  65251. };
  65252. return ArcFollowCamera;
  65253. }(BABYLON.TargetCamera));
  65254. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65255. })(BABYLON || (BABYLON = {}));
  65256. //# sourceMappingURL=babylon.followCamera.js.map
  65257. var BABYLON;
  65258. (function (BABYLON) {
  65259. // We're mainly based on the logic defined into the FreeCamera code
  65260. var UniversalCamera = /** @class */ (function (_super) {
  65261. __extends(UniversalCamera, _super);
  65262. //-- end properties for backward compatibility for inputs
  65263. function UniversalCamera(name, position, scene) {
  65264. var _this = _super.call(this, name, position, scene) || this;
  65265. _this.inputs.addGamepad();
  65266. return _this;
  65267. }
  65268. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65269. //-- Begin properties for backward compatibility for inputs
  65270. get: function () {
  65271. var gamepad = this.inputs.attached["gamepad"];
  65272. if (gamepad)
  65273. return gamepad.gamepadAngularSensibility;
  65274. return 0;
  65275. },
  65276. set: function (value) {
  65277. var gamepad = this.inputs.attached["gamepad"];
  65278. if (gamepad)
  65279. gamepad.gamepadAngularSensibility = value;
  65280. },
  65281. enumerable: true,
  65282. configurable: true
  65283. });
  65284. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65285. get: function () {
  65286. var gamepad = this.inputs.attached["gamepad"];
  65287. if (gamepad)
  65288. return gamepad.gamepadMoveSensibility;
  65289. return 0;
  65290. },
  65291. set: function (value) {
  65292. var gamepad = this.inputs.attached["gamepad"];
  65293. if (gamepad)
  65294. gamepad.gamepadMoveSensibility = value;
  65295. },
  65296. enumerable: true,
  65297. configurable: true
  65298. });
  65299. UniversalCamera.prototype.getClassName = function () {
  65300. return "UniversalCamera";
  65301. };
  65302. return UniversalCamera;
  65303. }(BABYLON.TouchCamera));
  65304. BABYLON.UniversalCamera = UniversalCamera;
  65305. })(BABYLON || (BABYLON = {}));
  65306. //# sourceMappingURL=babylon.universalCamera.js.map
  65307. var BABYLON;
  65308. (function (BABYLON) {
  65309. // We're mainly based on the logic defined into the FreeCamera code
  65310. var GamepadCamera = /** @class */ (function (_super) {
  65311. __extends(GamepadCamera, _super);
  65312. //-- end properties for backward compatibility for inputs
  65313. function GamepadCamera(name, position, scene) {
  65314. return _super.call(this, name, position, scene) || this;
  65315. }
  65316. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65317. //-- Begin properties for backward compatibility for inputs
  65318. get: function () {
  65319. var gamepad = this.inputs.attached["gamepad"];
  65320. if (gamepad)
  65321. return gamepad.gamepadAngularSensibility;
  65322. return 0;
  65323. },
  65324. set: function (value) {
  65325. var gamepad = this.inputs.attached["gamepad"];
  65326. if (gamepad)
  65327. gamepad.gamepadAngularSensibility = value;
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65333. get: function () {
  65334. var gamepad = this.inputs.attached["gamepad"];
  65335. if (gamepad)
  65336. return gamepad.gamepadMoveSensibility;
  65337. return 0;
  65338. },
  65339. set: function (value) {
  65340. var gamepad = this.inputs.attached["gamepad"];
  65341. if (gamepad)
  65342. gamepad.gamepadMoveSensibility = value;
  65343. },
  65344. enumerable: true,
  65345. configurable: true
  65346. });
  65347. GamepadCamera.prototype.getClassName = function () {
  65348. return "GamepadCamera";
  65349. };
  65350. return GamepadCamera;
  65351. }(BABYLON.UniversalCamera));
  65352. BABYLON.GamepadCamera = GamepadCamera;
  65353. })(BABYLON || (BABYLON = {}));
  65354. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65355. var BABYLON;
  65356. (function (BABYLON) {
  65357. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65358. function PostProcessRenderPipelineManager() {
  65359. this._renderPipelines = {};
  65360. }
  65361. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65362. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65363. };
  65364. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65365. if (unique === void 0) { unique = false; }
  65366. var renderPipeline = this._renderPipelines[renderPipelineName];
  65367. if (!renderPipeline) {
  65368. return;
  65369. }
  65370. renderPipeline._attachCameras(cameras, unique);
  65371. };
  65372. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65373. var renderPipeline = this._renderPipelines[renderPipelineName];
  65374. if (!renderPipeline) {
  65375. return;
  65376. }
  65377. renderPipeline._detachCameras(cameras);
  65378. };
  65379. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65380. var renderPipeline = this._renderPipelines[renderPipelineName];
  65381. if (!renderPipeline) {
  65382. return;
  65383. }
  65384. renderPipeline._enableEffect(renderEffectName, cameras);
  65385. };
  65386. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65387. var renderPipeline = this._renderPipelines[renderPipelineName];
  65388. if (!renderPipeline) {
  65389. return;
  65390. }
  65391. renderPipeline._disableEffect(renderEffectName, cameras);
  65392. };
  65393. PostProcessRenderPipelineManager.prototype.update = function () {
  65394. for (var renderPipelineName in this._renderPipelines) {
  65395. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65396. var pipeline = this._renderPipelines[renderPipelineName];
  65397. if (!pipeline.isSupported) {
  65398. pipeline.dispose();
  65399. delete this._renderPipelines[renderPipelineName];
  65400. }
  65401. else {
  65402. pipeline._update();
  65403. }
  65404. }
  65405. }
  65406. };
  65407. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65408. for (var renderPipelineName in this._renderPipelines) {
  65409. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65410. var pipeline = this._renderPipelines[renderPipelineName];
  65411. pipeline._rebuild();
  65412. }
  65413. }
  65414. };
  65415. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65416. for (var renderPipelineName in this._renderPipelines) {
  65417. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65418. var pipeline = this._renderPipelines[renderPipelineName];
  65419. pipeline.dispose();
  65420. }
  65421. }
  65422. };
  65423. return PostProcessRenderPipelineManager;
  65424. }());
  65425. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65426. })(BABYLON || (BABYLON = {}));
  65427. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65428. var BABYLON;
  65429. (function (BABYLON) {
  65430. /**
  65431. * This represents a set of one or more post processes in Babylon.
  65432. * A post process can be used to apply a shader to a texture after it is rendered.
  65433. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65434. */
  65435. var PostProcessRenderEffect = /** @class */ (function () {
  65436. /**
  65437. * Instantiates a post process render effect.
  65438. * A post process can be used to apply a shader to a texture after it is rendered.
  65439. * @param engine The engine the effect is tied to
  65440. * @param name The name of the effect
  65441. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65442. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65443. */
  65444. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65445. this._name = name;
  65446. this._singleInstance = singleInstance || true;
  65447. this._getPostProcesses = getPostProcesses;
  65448. this._cameras = {};
  65449. this._indicesForCamera = {};
  65450. this._postProcesses = {};
  65451. }
  65452. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65453. /**
  65454. * Checks if all the post processes in the effect are supported.
  65455. */
  65456. get: function () {
  65457. for (var index in this._postProcesses) {
  65458. for (var ppIndex in this._postProcesses[index]) {
  65459. if (!this._postProcesses[index][ppIndex].isSupported) {
  65460. return false;
  65461. }
  65462. }
  65463. }
  65464. return true;
  65465. },
  65466. enumerable: true,
  65467. configurable: true
  65468. });
  65469. /**
  65470. * Updates the current state of the effect
  65471. */
  65472. PostProcessRenderEffect.prototype._update = function () {
  65473. };
  65474. /**
  65475. * Attaches the effect on cameras
  65476. * @param cameras The camera to attach to.
  65477. */
  65478. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65479. var _this = this;
  65480. var cameraKey;
  65481. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65482. if (!cams) {
  65483. return;
  65484. }
  65485. for (var i = 0; i < cams.length; i++) {
  65486. var camera = cams[i];
  65487. var cameraName = camera.name;
  65488. if (this._singleInstance) {
  65489. cameraKey = 0;
  65490. }
  65491. else {
  65492. cameraKey = cameraName;
  65493. }
  65494. if (!this._postProcesses[cameraKey]) {
  65495. var postProcess = this._getPostProcesses();
  65496. if (postProcess) {
  65497. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65498. }
  65499. }
  65500. if (!this._indicesForCamera[cameraName]) {
  65501. this._indicesForCamera[cameraName] = [];
  65502. }
  65503. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65504. var index = camera.attachPostProcess(postProcess);
  65505. _this._indicesForCamera[cameraName].push(index);
  65506. });
  65507. if (!this._cameras[cameraName]) {
  65508. this._cameras[cameraName] = camera;
  65509. }
  65510. }
  65511. };
  65512. /**
  65513. * Detatches the effect on cameras
  65514. * @param cameras The camera to detatch from.
  65515. */
  65516. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65517. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65518. if (!cams) {
  65519. return;
  65520. }
  65521. for (var i = 0; i < cams.length; i++) {
  65522. var camera = cams[i];
  65523. var cameraName = camera.name;
  65524. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65525. camera.detachPostProcess(postProcess);
  65526. });
  65527. if (this._cameras[cameraName]) {
  65528. //this._indicesForCamera.splice(index, 1);
  65529. this._cameras[cameraName] = null;
  65530. }
  65531. }
  65532. };
  65533. /**
  65534. * Enables the effect on given cameras
  65535. * @param cameras The camera to enable.
  65536. */
  65537. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65538. var _this = this;
  65539. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65540. if (!cams) {
  65541. return;
  65542. }
  65543. for (var i = 0; i < cams.length; i++) {
  65544. var camera = cams[i];
  65545. var cameraName = camera.name;
  65546. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65547. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65548. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65549. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65550. });
  65551. }
  65552. }
  65553. }
  65554. };
  65555. /**
  65556. * Disables the effect on the given cameras
  65557. * @param cameras The camera to disable.
  65558. */
  65559. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65560. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65561. if (!cams) {
  65562. return;
  65563. }
  65564. for (var i = 0; i < cams.length; i++) {
  65565. var camera = cams[i];
  65566. var cameraName = camera.name;
  65567. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65568. camera.detachPostProcess(postProcess);
  65569. });
  65570. }
  65571. };
  65572. /**
  65573. * Gets a list of the post processes contained in the effect.
  65574. * @param camera The camera to get the post processes on.
  65575. * @returns The list of the post processes in the effect.
  65576. */
  65577. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65578. if (this._singleInstance) {
  65579. return this._postProcesses[0];
  65580. }
  65581. else {
  65582. if (!camera) {
  65583. return null;
  65584. }
  65585. return this._postProcesses[camera.name];
  65586. }
  65587. };
  65588. return PostProcessRenderEffect;
  65589. }());
  65590. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65591. })(BABYLON || (BABYLON = {}));
  65592. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65593. var BABYLON;
  65594. (function (BABYLON) {
  65595. var PostProcessRenderPipeline = /** @class */ (function () {
  65596. function PostProcessRenderPipeline(engine, name) {
  65597. this.engine = engine;
  65598. this._name = name;
  65599. this._renderEffects = {};
  65600. this._renderEffectsForIsolatedPass = new Array();
  65601. this._cameras = [];
  65602. }
  65603. PostProcessRenderPipeline.prototype.getClassName = function () {
  65604. return "PostProcessRenderPipeline";
  65605. };
  65606. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65607. get: function () {
  65608. for (var renderEffectName in this._renderEffects) {
  65609. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65610. if (!this._renderEffects[renderEffectName].isSupported) {
  65611. return false;
  65612. }
  65613. }
  65614. }
  65615. return true;
  65616. },
  65617. enumerable: true,
  65618. configurable: true
  65619. });
  65620. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65621. this._renderEffects[renderEffect._name] = renderEffect;
  65622. };
  65623. // private
  65624. PostProcessRenderPipeline.prototype._rebuild = function () {
  65625. };
  65626. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65627. var renderEffects = this._renderEffects[renderEffectName];
  65628. if (!renderEffects) {
  65629. return;
  65630. }
  65631. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65632. };
  65633. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65634. var renderEffects = this._renderEffects[renderEffectName];
  65635. if (!renderEffects) {
  65636. return;
  65637. }
  65638. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65639. };
  65640. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65641. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65642. if (!cams) {
  65643. return;
  65644. }
  65645. var indicesToDelete = [];
  65646. var i;
  65647. for (i = 0; i < cams.length; i++) {
  65648. var camera = cams[i];
  65649. var cameraName = camera.name;
  65650. if (this._cameras.indexOf(camera) === -1) {
  65651. this._cameras[cameraName] = camera;
  65652. }
  65653. else if (unique) {
  65654. indicesToDelete.push(i);
  65655. }
  65656. }
  65657. for (i = 0; i < indicesToDelete.length; i++) {
  65658. cameras.splice(indicesToDelete[i], 1);
  65659. }
  65660. for (var renderEffectName in this._renderEffects) {
  65661. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65662. this._renderEffects[renderEffectName]._attachCameras(cams);
  65663. }
  65664. }
  65665. };
  65666. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65667. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65668. if (!cams) {
  65669. return;
  65670. }
  65671. for (var renderEffectName in this._renderEffects) {
  65672. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65673. this._renderEffects[renderEffectName]._detachCameras(cams);
  65674. }
  65675. }
  65676. for (var i = 0; i < cams.length; i++) {
  65677. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65678. }
  65679. };
  65680. PostProcessRenderPipeline.prototype._update = function () {
  65681. for (var renderEffectName in this._renderEffects) {
  65682. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65683. this._renderEffects[renderEffectName]._update();
  65684. }
  65685. }
  65686. for (var i = 0; i < this._cameras.length; i++) {
  65687. var cameraName = this._cameras[i].name;
  65688. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65689. this._renderEffectsForIsolatedPass[cameraName]._update();
  65690. }
  65691. }
  65692. };
  65693. PostProcessRenderPipeline.prototype._reset = function () {
  65694. this._renderEffects = {};
  65695. this._renderEffectsForIsolatedPass = new Array();
  65696. };
  65697. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65698. // 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)
  65699. var effectKeys = Object.keys(this._renderEffects);
  65700. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65701. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65702. if (postProcesses) {
  65703. postProcesses[0].samples = 4;
  65704. return true;
  65705. }
  65706. }
  65707. return false;
  65708. };
  65709. PostProcessRenderPipeline.prototype.dispose = function () {
  65710. // Must be implemented by children
  65711. };
  65712. __decorate([
  65713. BABYLON.serialize()
  65714. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65715. return PostProcessRenderPipeline;
  65716. }());
  65717. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65718. })(BABYLON || (BABYLON = {}));
  65719. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65720. var BABYLON;
  65721. (function (BABYLON) {
  65722. /**
  65723. * This represents a depth renderer in Babylon.
  65724. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65725. */
  65726. var DepthRenderer = /** @class */ (function () {
  65727. /**
  65728. * Instantiates a depth renderer
  65729. * @param scene The scene the renderer belongs to
  65730. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65731. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65732. */
  65733. function DepthRenderer(scene, type, camera) {
  65734. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65735. if (camera === void 0) { camera = null; }
  65736. var _this = this;
  65737. this._scene = scene;
  65738. this._camera = camera;
  65739. var engine = scene.getEngine();
  65740. // Render target
  65741. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65742. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65743. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65744. this._depthMap.refreshRate = 1;
  65745. this._depthMap.renderParticles = false;
  65746. this._depthMap.renderList = null;
  65747. // Camera to get depth map from to support multiple concurrent cameras
  65748. this._depthMap.activeCamera = this._camera;
  65749. this._depthMap.ignoreCameraViewport = true;
  65750. this._depthMap.useCameraPostProcesses = false;
  65751. // set default depth value to 1.0 (far away)
  65752. this._depthMap.onClearObservable.add(function (engine) {
  65753. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65754. });
  65755. // Custom render function
  65756. var renderSubMesh = function (subMesh) {
  65757. var mesh = subMesh.getRenderingMesh();
  65758. var scene = _this._scene;
  65759. var engine = scene.getEngine();
  65760. var material = subMesh.getMaterial();
  65761. if (!material) {
  65762. return;
  65763. }
  65764. // Culling and reverse (right handed system)
  65765. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65766. // Managing instances
  65767. var batch = mesh._getInstancesRenderList(subMesh._id);
  65768. if (batch.mustReturn) {
  65769. return;
  65770. }
  65771. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65772. var camera = _this._camera || scene.activeCamera;
  65773. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65774. engine.enableEffect(_this._effect);
  65775. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65776. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65777. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65778. // Alpha test
  65779. if (material && material.needAlphaTesting()) {
  65780. var alphaTexture = material.getAlphaTestTexture();
  65781. if (alphaTexture) {
  65782. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65783. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65784. }
  65785. }
  65786. // Bones
  65787. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65788. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65789. }
  65790. // Draw
  65791. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65792. }
  65793. };
  65794. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65795. var index;
  65796. if (depthOnlySubMeshes.length) {
  65797. engine.setColorWrite(false);
  65798. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65799. renderSubMesh(depthOnlySubMeshes.data[index]);
  65800. }
  65801. engine.setColorWrite(true);
  65802. }
  65803. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65804. renderSubMesh(opaqueSubMeshes.data[index]);
  65805. }
  65806. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65807. renderSubMesh(alphaTestSubMeshes.data[index]);
  65808. }
  65809. };
  65810. }
  65811. /**
  65812. * Creates the depth rendering effect and checks if the effect is ready.
  65813. * @param subMesh The submesh to be used to render the depth map of
  65814. * @param useInstances If multiple world instances should be used
  65815. * @returns if the depth renderer is ready to render the depth map
  65816. */
  65817. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65818. var material = subMesh.getMaterial();
  65819. if (material.disableDepthWrite) {
  65820. return false;
  65821. }
  65822. var defines = [];
  65823. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65824. var mesh = subMesh.getMesh();
  65825. // Alpha test
  65826. if (material && material.needAlphaTesting()) {
  65827. defines.push("#define ALPHATEST");
  65828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65829. attribs.push(BABYLON.VertexBuffer.UVKind);
  65830. defines.push("#define UV1");
  65831. }
  65832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65834. defines.push("#define UV2");
  65835. }
  65836. }
  65837. // Bones
  65838. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65839. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65840. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65841. if (mesh.numBoneInfluencers > 4) {
  65842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65844. }
  65845. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65846. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65847. }
  65848. else {
  65849. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65850. }
  65851. // Instances
  65852. if (useInstances) {
  65853. defines.push("#define INSTANCES");
  65854. attribs.push("world0");
  65855. attribs.push("world1");
  65856. attribs.push("world2");
  65857. attribs.push("world3");
  65858. }
  65859. // Get correct effect
  65860. var join = defines.join("\n");
  65861. if (this._cachedDefines !== join) {
  65862. this._cachedDefines = join;
  65863. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65864. }
  65865. return this._effect.isReady();
  65866. };
  65867. /**
  65868. * Gets the texture which the depth map will be written to.
  65869. * @returns The depth map texture
  65870. */
  65871. DepthRenderer.prototype.getDepthMap = function () {
  65872. return this._depthMap;
  65873. };
  65874. /**
  65875. * Disposes of the depth renderer.
  65876. */
  65877. DepthRenderer.prototype.dispose = function () {
  65878. this._depthMap.dispose();
  65879. };
  65880. return DepthRenderer;
  65881. }());
  65882. BABYLON.DepthRenderer = DepthRenderer;
  65883. })(BABYLON || (BABYLON = {}));
  65884. //# sourceMappingURL=babylon.depthRenderer.js.map
  65885. var BABYLON;
  65886. (function (BABYLON) {
  65887. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65888. __extends(SSAORenderingPipeline, _super);
  65889. /**
  65890. * @constructor
  65891. * @param {string} name - The rendering pipeline name
  65892. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65893. * @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 }
  65894. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65895. */
  65896. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65897. var _this = _super.call(this, scene.getEngine(), name) || this;
  65898. // Members
  65899. /**
  65900. * The PassPostProcess id in the pipeline that contains the original scene color
  65901. * @type {string}
  65902. */
  65903. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65904. /**
  65905. * The SSAO PostProcess id in the pipeline
  65906. * @type {string}
  65907. */
  65908. _this.SSAORenderEffect = "SSAORenderEffect";
  65909. /**
  65910. * The horizontal blur PostProcess id in the pipeline
  65911. * @type {string}
  65912. */
  65913. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65914. /**
  65915. * The vertical blur PostProcess id in the pipeline
  65916. * @type {string}
  65917. */
  65918. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65919. /**
  65920. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65921. * @type {string}
  65922. */
  65923. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65924. /**
  65925. * The output strength of the SSAO post-process. Default value is 1.0.
  65926. * @type {number}
  65927. */
  65928. _this.totalStrength = 1.0;
  65929. /**
  65930. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65931. * @type {number}
  65932. */
  65933. _this.radius = 0.0001;
  65934. /**
  65935. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65936. * Must not be equal to fallOff and superior to fallOff.
  65937. * Default value is 0.975
  65938. * @type {number}
  65939. */
  65940. _this.area = 0.0075;
  65941. /**
  65942. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65943. * Must not be equal to area and inferior to area.
  65944. * Default value is 0.0
  65945. * @type {number}
  65946. */
  65947. _this.fallOff = 0.000001;
  65948. /**
  65949. * The base color of the SSAO post-process
  65950. * The final result is "base + ssao" between [0, 1]
  65951. * @type {number}
  65952. */
  65953. _this.base = 0.5;
  65954. _this._firstUpdate = true;
  65955. _this._scene = scene;
  65956. // Set up assets
  65957. _this._createRandomTexture();
  65958. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65959. var ssaoRatio = ratio.ssaoRatio || ratio;
  65960. var combineRatio = ratio.combineRatio || ratio;
  65961. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65962. _this._createSSAOPostProcess(ssaoRatio);
  65963. _this._createBlurPostProcess(ssaoRatio);
  65964. _this._createSSAOCombinePostProcess(combineRatio);
  65965. // Set up pipeline
  65966. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65967. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65968. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65969. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65970. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65971. // Finish
  65972. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65973. if (cameras)
  65974. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65975. return _this;
  65976. }
  65977. // Public Methods
  65978. /**
  65979. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65980. */
  65981. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65982. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65983. for (var i = 0; i < this._scene.cameras.length; i++) {
  65984. var camera = this._scene.cameras[i];
  65985. this._originalColorPostProcess.dispose(camera);
  65986. this._ssaoPostProcess.dispose(camera);
  65987. this._blurHPostProcess.dispose(camera);
  65988. this._blurVPostProcess.dispose(camera);
  65989. this._ssaoCombinePostProcess.dispose(camera);
  65990. }
  65991. this._randomTexture.dispose();
  65992. if (disableDepthRender)
  65993. this._scene.disableDepthRenderer();
  65994. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65995. _super.prototype.dispose.call(this);
  65996. };
  65997. // Private Methods
  65998. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65999. var _this = this;
  66000. var size = 16;
  66001. 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);
  66002. 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);
  66003. this._blurHPostProcess.onActivateObservable.add(function () {
  66004. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66005. _this._blurHPostProcess.kernel = size * dw;
  66006. });
  66007. this._blurVPostProcess.onActivateObservable.add(function () {
  66008. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66009. _this._blurVPostProcess.kernel = size * dw;
  66010. });
  66011. };
  66012. SSAORenderingPipeline.prototype._rebuild = function () {
  66013. this._firstUpdate = true;
  66014. _super.prototype._rebuild.call(this);
  66015. };
  66016. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66017. var _this = this;
  66018. var numSamples = 16;
  66019. var sampleSphere = [
  66020. 0.5381, 0.1856, -0.4319,
  66021. 0.1379, 0.2486, 0.4430,
  66022. 0.3371, 0.5679, -0.0057,
  66023. -0.6999, -0.0451, -0.0019,
  66024. 0.0689, -0.1598, -0.8547,
  66025. 0.0560, 0.0069, -0.1843,
  66026. -0.0146, 0.1402, 0.0762,
  66027. 0.0100, -0.1924, -0.0344,
  66028. -0.3577, -0.5301, -0.4358,
  66029. -0.3169, 0.1063, 0.0158,
  66030. 0.0103, -0.5869, 0.0046,
  66031. -0.0897, -0.4940, 0.3287,
  66032. 0.7119, -0.0154, -0.0918,
  66033. -0.0533, 0.0596, -0.5411,
  66034. 0.0352, -0.0631, 0.5460,
  66035. -0.4776, 0.2847, -0.0271
  66036. ];
  66037. var samplesFactor = 1.0 / numSamples;
  66038. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66039. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66040. "area", "fallOff", "base", "range", "viewport"
  66041. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66042. this._ssaoPostProcess.onApply = function (effect) {
  66043. if (_this._firstUpdate) {
  66044. effect.setArray3("sampleSphere", sampleSphere);
  66045. effect.setFloat("samplesFactor", samplesFactor);
  66046. effect.setFloat("randTextureTiles", 4.0);
  66047. }
  66048. effect.setFloat("totalStrength", _this.totalStrength);
  66049. effect.setFloat("radius", _this.radius);
  66050. effect.setFloat("area", _this.area);
  66051. effect.setFloat("fallOff", _this.fallOff);
  66052. effect.setFloat("base", _this.base);
  66053. effect.setTexture("textureSampler", _this._depthTexture);
  66054. effect.setTexture("randomSampler", _this._randomTexture);
  66055. };
  66056. };
  66057. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66058. var _this = this;
  66059. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66060. this._ssaoCombinePostProcess.onApply = function (effect) {
  66061. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66062. };
  66063. };
  66064. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66065. var size = 512;
  66066. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66067. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66068. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66069. var context = this._randomTexture.getContext();
  66070. var rand = function (min, max) {
  66071. return Math.random() * (max - min) + min;
  66072. };
  66073. var randVector = BABYLON.Vector3.Zero();
  66074. for (var x = 0; x < size; x++) {
  66075. for (var y = 0; y < size; y++) {
  66076. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66077. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66078. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66079. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66080. context.fillRect(x, y, 1, 1);
  66081. }
  66082. }
  66083. this._randomTexture.update(false);
  66084. };
  66085. __decorate([
  66086. BABYLON.serialize()
  66087. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66088. __decorate([
  66089. BABYLON.serialize()
  66090. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66091. __decorate([
  66092. BABYLON.serialize()
  66093. ], SSAORenderingPipeline.prototype, "area", void 0);
  66094. __decorate([
  66095. BABYLON.serialize()
  66096. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66097. __decorate([
  66098. BABYLON.serialize()
  66099. ], SSAORenderingPipeline.prototype, "base", void 0);
  66100. return SSAORenderingPipeline;
  66101. }(BABYLON.PostProcessRenderPipeline));
  66102. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66103. })(BABYLON || (BABYLON = {}));
  66104. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66105. var BABYLON;
  66106. (function (BABYLON) {
  66107. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66108. __extends(SSAO2RenderingPipeline, _super);
  66109. /**
  66110. * @constructor
  66111. * @param {string} name - The rendering pipeline name
  66112. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66113. * @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 }
  66114. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66115. */
  66116. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66117. var _this = _super.call(this, scene.getEngine(), name) || this;
  66118. // Members
  66119. /**
  66120. * The PassPostProcess id in the pipeline that contains the original scene color
  66121. * @type {string}
  66122. */
  66123. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66124. /**
  66125. * The SSAO PostProcess id in the pipeline
  66126. * @type {string}
  66127. */
  66128. _this.SSAORenderEffect = "SSAORenderEffect";
  66129. /**
  66130. * The horizontal blur PostProcess id in the pipeline
  66131. * @type {string}
  66132. */
  66133. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66134. /**
  66135. * The vertical blur PostProcess id in the pipeline
  66136. * @type {string}
  66137. */
  66138. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66139. /**
  66140. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66141. * @type {string}
  66142. */
  66143. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66144. /**
  66145. * The output strength of the SSAO post-process. Default value is 1.0.
  66146. * @type {number}
  66147. */
  66148. _this.totalStrength = 1.0;
  66149. /**
  66150. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66151. * @type {number}
  66152. */
  66153. _this.maxZ = 100.0;
  66154. /**
  66155. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66156. * @type {number}
  66157. */
  66158. _this.minZAspect = 0.2;
  66159. /**
  66160. * Number of samples used for the SSAO calculations. Default value is 8
  66161. * @type {number}
  66162. */
  66163. _this._samples = 8;
  66164. /**
  66165. * Are we using bilateral blur ?
  66166. * @type {boolean}
  66167. */
  66168. _this._expensiveBlur = true;
  66169. /**
  66170. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66171. * @type {number}
  66172. */
  66173. _this.radius = 2.0;
  66174. /**
  66175. * The base color of the SSAO post-process
  66176. * The final result is "base + ssao" between [0, 1]
  66177. * @type {number}
  66178. */
  66179. _this.base = 0.1;
  66180. _this._firstUpdate = true;
  66181. _this._scene = scene;
  66182. if (!_this.isSupported) {
  66183. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66184. return _this;
  66185. }
  66186. var ssaoRatio = ratio.ssaoRatio || ratio;
  66187. var blurRatio = ratio.blurRatio || ratio;
  66188. // Set up assets
  66189. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66190. _this._createRandomTexture();
  66191. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66192. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66193. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66194. _this._createSSAOPostProcess(1.0);
  66195. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66196. _this._createSSAOCombinePostProcess(blurRatio);
  66197. // Set up pipeline
  66198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66200. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66201. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66202. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66203. // Finish
  66204. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66205. if (cameras)
  66206. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66207. return _this;
  66208. }
  66209. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66210. get: function () {
  66211. return this._samples;
  66212. },
  66213. set: function (n) {
  66214. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66215. this._samples = n;
  66216. this._sampleSphere = this._generateHemisphere();
  66217. this._firstUpdate = true;
  66218. },
  66219. enumerable: true,
  66220. configurable: true
  66221. });
  66222. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66223. get: function () {
  66224. return this._expensiveBlur;
  66225. },
  66226. set: function (b) {
  66227. 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"]);
  66228. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66229. this._expensiveBlur = b;
  66230. this._firstUpdate = true;
  66231. },
  66232. enumerable: true,
  66233. configurable: true
  66234. });
  66235. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66236. /**
  66237. * Support test.
  66238. * @type {boolean}
  66239. */
  66240. get: function () {
  66241. var engine = BABYLON.Engine.LastCreatedEngine;
  66242. if (!engine) {
  66243. return false;
  66244. }
  66245. return engine.getCaps().drawBuffersExtension;
  66246. },
  66247. enumerable: true,
  66248. configurable: true
  66249. });
  66250. // Public Methods
  66251. /**
  66252. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66253. */
  66254. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66255. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66256. for (var i = 0; i < this._scene.cameras.length; i++) {
  66257. var camera = this._scene.cameras[i];
  66258. this._originalColorPostProcess.dispose(camera);
  66259. this._ssaoPostProcess.dispose(camera);
  66260. this._blurHPostProcess.dispose(camera);
  66261. this._blurVPostProcess.dispose(camera);
  66262. this._ssaoCombinePostProcess.dispose(camera);
  66263. }
  66264. this._randomTexture.dispose();
  66265. if (disableGeometryBufferRenderer)
  66266. this._scene.disableGeometryBufferRenderer();
  66267. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66268. _super.prototype.dispose.call(this);
  66269. };
  66270. // Private Methods
  66271. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66272. var _this = this;
  66273. this._samplerOffsets = [];
  66274. var expensive = this.expensiveBlur;
  66275. for (var i = -8; i < 8; i++) {
  66276. this._samplerOffsets.push(i * 2 + 0.5);
  66277. }
  66278. 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");
  66279. this._blurHPostProcess.onApply = function (effect) {
  66280. if (!_this._scene.activeCamera) {
  66281. return;
  66282. }
  66283. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66284. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66285. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66286. effect.setFloat("radius", _this.radius);
  66287. effect.setTexture("depthSampler", _this._depthTexture);
  66288. if (_this._firstUpdate) {
  66289. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66290. }
  66291. };
  66292. 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");
  66293. this._blurVPostProcess.onApply = function (effect) {
  66294. if (!_this._scene.activeCamera) {
  66295. return;
  66296. }
  66297. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66298. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66299. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66300. effect.setFloat("radius", _this.radius);
  66301. effect.setTexture("depthSampler", _this._depthTexture);
  66302. if (_this._firstUpdate) {
  66303. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66304. _this._firstUpdate = false;
  66305. }
  66306. };
  66307. };
  66308. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66309. this._firstUpdate = true;
  66310. _super.prototype._rebuild.call(this);
  66311. };
  66312. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66313. var numSamples = this.samples;
  66314. var result = [];
  66315. var vector, scale;
  66316. var rand = function (min, max) {
  66317. return Math.random() * (max - min) + min;
  66318. };
  66319. var i = 0;
  66320. while (i < numSamples) {
  66321. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66322. vector.normalize();
  66323. scale = i / numSamples;
  66324. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66325. vector.scaleInPlace(scale);
  66326. result.push(vector.x, vector.y, vector.z);
  66327. i++;
  66328. }
  66329. return result;
  66330. };
  66331. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66332. var _this = this;
  66333. var numSamples = this.samples;
  66334. this._sampleSphere = this._generateHemisphere();
  66335. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66336. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66337. "base", "range", "projection", "near", "far", "texelSize",
  66338. "xViewport", "yViewport", "maxZ", "minZAspect"
  66339. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66340. this._ssaoPostProcess.onApply = function (effect) {
  66341. if (_this._firstUpdate) {
  66342. effect.setArray3("sampleSphere", _this._sampleSphere);
  66343. effect.setFloat("randTextureTiles", 4.0);
  66344. }
  66345. if (!_this._scene.activeCamera) {
  66346. return;
  66347. }
  66348. effect.setFloat("samplesFactor", 1 / _this.samples);
  66349. effect.setFloat("totalStrength", _this.totalStrength);
  66350. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66351. effect.setFloat("radius", _this.radius);
  66352. effect.setFloat("maxZ", _this.maxZ);
  66353. effect.setFloat("minZAspect", _this.minZAspect);
  66354. effect.setFloat("base", _this.base);
  66355. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66356. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66357. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66358. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66359. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66360. effect.setTexture("textureSampler", _this._depthTexture);
  66361. effect.setTexture("normalSampler", _this._normalTexture);
  66362. effect.setTexture("randomSampler", _this._randomTexture);
  66363. };
  66364. };
  66365. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66366. var _this = this;
  66367. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66368. this._ssaoCombinePostProcess.onApply = function (effect) {
  66369. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66370. };
  66371. };
  66372. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66373. var size = 512;
  66374. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66375. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66376. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66377. var context = this._randomTexture.getContext();
  66378. var rand = function (min, max) {
  66379. return Math.random() * (max - min) + min;
  66380. };
  66381. var randVector = BABYLON.Vector3.Zero();
  66382. for (var x = 0; x < size; x++) {
  66383. for (var y = 0; y < size; y++) {
  66384. randVector.x = rand(0.0, 1.0);
  66385. randVector.y = rand(0.0, 1.0);
  66386. randVector.z = 0.0;
  66387. randVector.normalize();
  66388. randVector.scaleInPlace(255);
  66389. randVector.x = Math.floor(randVector.x);
  66390. randVector.y = Math.floor(randVector.y);
  66391. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66392. context.fillRect(x, y, 1, 1);
  66393. }
  66394. }
  66395. this._randomTexture.update(false);
  66396. };
  66397. __decorate([
  66398. BABYLON.serialize()
  66399. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66400. __decorate([
  66401. BABYLON.serialize()
  66402. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66403. __decorate([
  66404. BABYLON.serialize()
  66405. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66406. __decorate([
  66407. BABYLON.serialize("samples")
  66408. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66409. __decorate([
  66410. BABYLON.serialize("expensiveBlur")
  66411. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66412. __decorate([
  66413. BABYLON.serialize()
  66414. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66415. __decorate([
  66416. BABYLON.serialize()
  66417. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66418. return SSAO2RenderingPipeline;
  66419. }(BABYLON.PostProcessRenderPipeline));
  66420. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66421. })(BABYLON || (BABYLON = {}));
  66422. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66423. // BABYLON.JS Chromatic Aberration GLSL Shader
  66424. // Author: Olivier Guyot
  66425. // Separates very slightly R, G and B colors on the edges of the screen
  66426. // Inspired by Francois Tarlier & Martins Upitis
  66427. var BABYLON;
  66428. (function (BABYLON) {
  66429. var LensRenderingPipeline = /** @class */ (function (_super) {
  66430. __extends(LensRenderingPipeline, _super);
  66431. /**
  66432. * @constructor
  66433. *
  66434. * Effect parameters are as follow:
  66435. * {
  66436. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66437. * edge_blur: number; // from 0 to x (1 for realism)
  66438. * distortion: number; // from 0 to x (1 for realism)
  66439. * grain_amount: number; // from 0 to 1
  66440. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66441. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66442. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66443. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66444. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66445. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66446. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66447. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66448. * }
  66449. * Note: if an effect parameter is unset, effect is disabled
  66450. *
  66451. * @param {string} name - The rendering pipeline name
  66452. * @param {object} parameters - An object containing all parameters (see above)
  66453. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66454. * @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)
  66455. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66456. */
  66457. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66458. if (ratio === void 0) { ratio = 1.0; }
  66459. var _this = _super.call(this, scene.getEngine(), name) || this;
  66460. // Lens effects can be of the following:
  66461. // - chromatic aberration (slight shift of RGB colors)
  66462. // - blur on the edge of the lens
  66463. // - lens distortion
  66464. // - depth-of-field blur & highlights enhancing
  66465. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66466. // - grain effect (noise or custom texture)
  66467. // Two additional texture samplers are needed:
  66468. // - depth map (for depth-of-field)
  66469. // - grain texture
  66470. /**
  66471. * The chromatic aberration PostProcess id in the pipeline
  66472. * @type {string}
  66473. */
  66474. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66475. /**
  66476. * The highlights enhancing PostProcess id in the pipeline
  66477. * @type {string}
  66478. */
  66479. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66480. /**
  66481. * The depth-of-field PostProcess id in the pipeline
  66482. * @type {string}
  66483. */
  66484. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66485. _this._scene = scene;
  66486. // Fetch texture samplers
  66487. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66488. if (parameters.grain_texture) {
  66489. _this._grainTexture = parameters.grain_texture;
  66490. }
  66491. else {
  66492. _this._createGrainTexture();
  66493. }
  66494. // save parameters
  66495. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66496. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66497. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66498. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66499. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66500. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66501. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66502. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66503. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66504. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66505. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66506. // Create effects
  66507. _this._createChromaticAberrationPostProcess(ratio);
  66508. _this._createHighlightsPostProcess(ratio);
  66509. _this._createDepthOfFieldPostProcess(ratio / 4);
  66510. // Set up pipeline
  66511. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66512. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66514. if (_this._highlightsGain === -1) {
  66515. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66516. }
  66517. // Finish
  66518. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66519. if (cameras) {
  66520. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66521. }
  66522. return _this;
  66523. }
  66524. // public methods (self explanatory)
  66525. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66526. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66527. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66528. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66529. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66530. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66531. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66532. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66533. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66534. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66535. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66536. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66537. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66538. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66539. };
  66540. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66541. this._highlightsPostProcess.updateEffect();
  66542. };
  66543. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66544. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66545. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66546. this._highlightsGain = amount;
  66547. };
  66548. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66549. if (this._highlightsGain === -1) {
  66550. this._highlightsGain = 1.0;
  66551. }
  66552. this._highlightsThreshold = amount;
  66553. };
  66554. LensRenderingPipeline.prototype.disableHighlights = function () {
  66555. this._highlightsGain = -1;
  66556. };
  66557. /**
  66558. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66559. */
  66560. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66561. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66562. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66563. this._chromaticAberrationPostProcess = null;
  66564. this._highlightsPostProcess = null;
  66565. this._depthOfFieldPostProcess = null;
  66566. this._grainTexture.dispose();
  66567. if (disableDepthRender)
  66568. this._scene.disableDepthRenderer();
  66569. };
  66570. // colors shifting and distortion
  66571. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66572. var _this = this;
  66573. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66574. [], // samplers
  66575. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66576. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66577. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66578. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66579. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66580. };
  66581. };
  66582. // highlights enhancing
  66583. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66584. var _this = this;
  66585. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66586. [], // samplers
  66587. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66588. this._highlightsPostProcess.onApply = function (effect) {
  66589. effect.setFloat('gain', _this._highlightsGain);
  66590. effect.setFloat('threshold', _this._highlightsThreshold);
  66591. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66592. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66593. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66594. };
  66595. };
  66596. // colors shifting and distortion
  66597. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66598. var _this = this;
  66599. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66600. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66601. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66602. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66603. this._depthOfFieldPostProcess.onApply = function (effect) {
  66604. effect.setTexture("depthSampler", _this._depthTexture);
  66605. effect.setTexture("grainSampler", _this._grainTexture);
  66606. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66607. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66608. effect.setFloat('grain_amount', _this._grainAmount);
  66609. effect.setBool('blur_noise', _this._blurNoise);
  66610. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66611. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66612. effect.setFloat('distortion', _this._distortion);
  66613. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66614. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66615. effect.setFloat('aperture', _this._dofAperture);
  66616. effect.setFloat('darken', _this._dofDarken);
  66617. effect.setFloat('edge_blur', _this._edgeBlur);
  66618. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66619. if (_this._scene.activeCamera) {
  66620. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66621. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66622. }
  66623. };
  66624. };
  66625. // creates a black and white random noise texture, 512x512
  66626. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66627. var size = 512;
  66628. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66629. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66630. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66631. var context = this._grainTexture.getContext();
  66632. var rand = function (min, max) {
  66633. return Math.random() * (max - min) + min;
  66634. };
  66635. var value;
  66636. for (var x = 0; x < size; x++) {
  66637. for (var y = 0; y < size; y++) {
  66638. value = Math.floor(rand(0.42, 0.58) * 255);
  66639. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66640. context.fillRect(x, y, 1, 1);
  66641. }
  66642. }
  66643. this._grainTexture.update(false);
  66644. };
  66645. return LensRenderingPipeline;
  66646. }(BABYLON.PostProcessRenderPipeline));
  66647. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66648. })(BABYLON || (BABYLON = {}));
  66649. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66650. var BABYLON;
  66651. (function (BABYLON) {
  66652. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66653. __extends(StandardRenderingPipeline, _super);
  66654. /**
  66655. * @constructor
  66656. * @param {string} name - The rendering pipeline name
  66657. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66658. * @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)
  66659. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66660. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66661. */
  66662. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66663. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66664. var _this = _super.call(this, scene.getEngine(), name) || this;
  66665. _this.downSampleX4PostProcess = null;
  66666. _this.brightPassPostProcess = null;
  66667. _this.blurHPostProcesses = [];
  66668. _this.blurVPostProcesses = [];
  66669. _this.textureAdderPostProcess = null;
  66670. _this.volumetricLightPostProcess = null;
  66671. _this.volumetricLightSmoothXPostProcess = null;
  66672. _this.volumetricLightSmoothYPostProcess = null;
  66673. _this.volumetricLightMergePostProces = null;
  66674. _this.volumetricLightFinalPostProcess = null;
  66675. _this.luminancePostProcess = null;
  66676. _this.luminanceDownSamplePostProcesses = [];
  66677. _this.hdrPostProcess = null;
  66678. _this.textureAdderFinalPostProcess = null;
  66679. _this.lensFlareFinalPostProcess = null;
  66680. _this.hdrFinalPostProcess = null;
  66681. _this.lensFlarePostProcess = null;
  66682. _this.lensFlareComposePostProcess = null;
  66683. _this.motionBlurPostProcess = null;
  66684. _this.depthOfFieldPostProcess = null;
  66685. // Values
  66686. _this.brightThreshold = 1.0;
  66687. _this.blurWidth = 512.0;
  66688. _this.horizontalBlur = false;
  66689. _this.exposure = 1.0;
  66690. _this.lensTexture = null;
  66691. _this.volumetricLightCoefficient = 0.2;
  66692. _this.volumetricLightPower = 4.0;
  66693. _this.volumetricLightBlurScale = 64.0;
  66694. _this.sourceLight = null;
  66695. _this.hdrMinimumLuminance = 1.0;
  66696. _this.hdrDecreaseRate = 0.5;
  66697. _this.hdrIncreaseRate = 0.5;
  66698. _this.lensColorTexture = null;
  66699. _this.lensFlareStrength = 20.0;
  66700. _this.lensFlareGhostDispersal = 1.4;
  66701. _this.lensFlareHaloWidth = 0.7;
  66702. _this.lensFlareDistortionStrength = 16.0;
  66703. _this.lensStarTexture = null;
  66704. _this.lensFlareDirtTexture = null;
  66705. _this.depthOfFieldDistance = 10.0;
  66706. _this.depthOfFieldBlurWidth = 64.0;
  66707. _this.motionStrength = 1.0;
  66708. // IAnimatable
  66709. _this.animations = [];
  66710. _this._currentDepthOfFieldSource = null;
  66711. _this._hdrCurrentLuminance = 1.0;
  66712. // Getters and setters
  66713. _this._bloomEnabled = true;
  66714. _this._depthOfFieldEnabled = false;
  66715. _this._vlsEnabled = false;
  66716. _this._lensFlareEnabled = false;
  66717. _this._hdrEnabled = false;
  66718. _this._motionBlurEnabled = false;
  66719. _this._motionBlurSamples = 64.0;
  66720. _this._volumetricLightStepsCount = 50.0;
  66721. _this._cameras = cameras || [];
  66722. // Initialize
  66723. _this._scene = scene;
  66724. _this._basePostProcess = originalPostProcess;
  66725. _this._ratio = ratio;
  66726. // Misc
  66727. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66728. // Finish
  66729. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66730. _this._buildPipeline();
  66731. return _this;
  66732. }
  66733. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66734. get: function () {
  66735. return this._bloomEnabled;
  66736. },
  66737. set: function (enabled) {
  66738. if (this._bloomEnabled === enabled) {
  66739. return;
  66740. }
  66741. this._bloomEnabled = enabled;
  66742. this._buildPipeline();
  66743. },
  66744. enumerable: true,
  66745. configurable: true
  66746. });
  66747. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66748. get: function () {
  66749. return this._depthOfFieldEnabled;
  66750. },
  66751. set: function (enabled) {
  66752. if (this._depthOfFieldEnabled === enabled) {
  66753. return;
  66754. }
  66755. this._depthOfFieldEnabled = enabled;
  66756. this._buildPipeline();
  66757. },
  66758. enumerable: true,
  66759. configurable: true
  66760. });
  66761. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66762. get: function () {
  66763. return this._lensFlareEnabled;
  66764. },
  66765. set: function (enabled) {
  66766. if (this._lensFlareEnabled === enabled) {
  66767. return;
  66768. }
  66769. this._lensFlareEnabled = enabled;
  66770. this._buildPipeline();
  66771. },
  66772. enumerable: true,
  66773. configurable: true
  66774. });
  66775. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66776. get: function () {
  66777. return this._hdrEnabled;
  66778. },
  66779. set: function (enabled) {
  66780. if (this._hdrEnabled === enabled) {
  66781. return;
  66782. }
  66783. this._hdrEnabled = enabled;
  66784. this._buildPipeline();
  66785. },
  66786. enumerable: true,
  66787. configurable: true
  66788. });
  66789. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66790. get: function () {
  66791. return this._vlsEnabled;
  66792. },
  66793. set: function (enabled) {
  66794. if (this._vlsEnabled === enabled) {
  66795. return;
  66796. }
  66797. if (enabled) {
  66798. var geometry = this._scene.enableGeometryBufferRenderer();
  66799. if (!geometry) {
  66800. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66801. return;
  66802. }
  66803. }
  66804. this._vlsEnabled = enabled;
  66805. this._buildPipeline();
  66806. },
  66807. enumerable: true,
  66808. configurable: true
  66809. });
  66810. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66811. get: function () {
  66812. return this._motionBlurEnabled;
  66813. },
  66814. set: function (enabled) {
  66815. if (this._motionBlurEnabled === enabled) {
  66816. return;
  66817. }
  66818. this._motionBlurEnabled = enabled;
  66819. this._buildPipeline();
  66820. },
  66821. enumerable: true,
  66822. configurable: true
  66823. });
  66824. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66825. get: function () {
  66826. return this._volumetricLightStepsCount;
  66827. },
  66828. set: function (count) {
  66829. if (this.volumetricLightPostProcess) {
  66830. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66831. }
  66832. this._volumetricLightStepsCount = count;
  66833. },
  66834. enumerable: true,
  66835. configurable: true
  66836. });
  66837. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66838. get: function () {
  66839. return this._motionBlurSamples;
  66840. },
  66841. set: function (samples) {
  66842. if (this.motionBlurPostProcess) {
  66843. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66844. }
  66845. this._motionBlurSamples = samples;
  66846. },
  66847. enumerable: true,
  66848. configurable: true
  66849. });
  66850. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66851. var _this = this;
  66852. var ratio = this._ratio;
  66853. var scene = this._scene;
  66854. this._disposePostProcesses();
  66855. this._reset();
  66856. // Create pass post-process
  66857. if (!this._basePostProcess) {
  66858. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66859. this.originalPostProcess.onApply = function (effect) {
  66860. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66861. };
  66862. }
  66863. else {
  66864. this.originalPostProcess = this._basePostProcess;
  66865. }
  66866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66867. this._currentDepthOfFieldSource = this.originalPostProcess;
  66868. if (this._vlsEnabled) {
  66869. // Create volumetric light
  66870. this._createVolumetricLightPostProcess(scene, ratio);
  66871. // Create volumetric light final post-process
  66872. 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);
  66873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66874. }
  66875. if (this._bloomEnabled) {
  66876. // Create down sample X4 post-process
  66877. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66878. // Create bright pass post-process
  66879. this._createBrightPassPostProcess(scene, ratio / 2);
  66880. // Create gaussian blur post-processes (down sampling blurs)
  66881. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66882. // Create texture adder post-process
  66883. this._createTextureAdderPostProcess(scene, ratio);
  66884. // Create depth-of-field source post-process
  66885. 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);
  66886. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66887. }
  66888. if (this._lensFlareEnabled) {
  66889. // Create lens flare post-process
  66890. this._createLensFlarePostProcess(scene, ratio);
  66891. // Create depth-of-field source post-process post lens-flare and disable it now
  66892. 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);
  66893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66894. }
  66895. if (this._hdrEnabled) {
  66896. // Create luminance
  66897. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66898. // Create HDR
  66899. this._createHdrPostProcess(scene, ratio);
  66900. // Create depth-of-field source post-process post hdr and disable it now
  66901. 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);
  66902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66903. }
  66904. if (this._depthOfFieldEnabled) {
  66905. // Create gaussian blur used by depth-of-field
  66906. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66907. // Create depth-of-field post-process
  66908. this._createDepthOfFieldPostProcess(scene, ratio);
  66909. }
  66910. if (this._motionBlurEnabled) {
  66911. // Create motion blur post-process
  66912. this._createMotionBlurPostProcess(scene, ratio);
  66913. }
  66914. if (this._cameras !== null) {
  66915. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66916. }
  66917. };
  66918. // Down Sample X4 Post-Processs
  66919. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66920. var _this = this;
  66921. var downSampleX4Offsets = new Array(32);
  66922. 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);
  66923. this.downSampleX4PostProcess.onApply = function (effect) {
  66924. var id = 0;
  66925. var width = _this.downSampleX4PostProcess.width;
  66926. var height = _this.downSampleX4PostProcess.height;
  66927. for (var i = -2; i < 2; i++) {
  66928. for (var j = -2; j < 2; j++) {
  66929. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66930. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66931. id += 2;
  66932. }
  66933. }
  66934. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66935. };
  66936. // Add to pipeline
  66937. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66938. };
  66939. // Brightpass Post-Process
  66940. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66941. var _this = this;
  66942. var brightOffsets = new Array(8);
  66943. 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);
  66944. this.brightPassPostProcess.onApply = function (effect) {
  66945. var sU = (1.0 / _this.brightPassPostProcess.width);
  66946. var sV = (1.0 / _this.brightPassPostProcess.height);
  66947. brightOffsets[0] = -0.5 * sU;
  66948. brightOffsets[1] = 0.5 * sV;
  66949. brightOffsets[2] = 0.5 * sU;
  66950. brightOffsets[3] = 0.5 * sV;
  66951. brightOffsets[4] = -0.5 * sU;
  66952. brightOffsets[5] = -0.5 * sV;
  66953. brightOffsets[6] = 0.5 * sU;
  66954. brightOffsets[7] = -0.5 * sV;
  66955. effect.setArray2("dsOffsets", brightOffsets);
  66956. effect.setFloat("brightThreshold", _this.brightThreshold);
  66957. };
  66958. // Add to pipeline
  66959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66960. };
  66961. // Create blur H&V post-processes
  66962. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66963. var _this = this;
  66964. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66965. var engine = scene.getEngine();
  66966. 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);
  66967. 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);
  66968. blurX.onActivateObservable.add(function () {
  66969. var dw = blurX.width / engine.getRenderWidth();
  66970. blurX.kernel = _this[blurWidthKey] * dw;
  66971. });
  66972. blurY.onActivateObservable.add(function () {
  66973. var dw = blurY.height / engine.getRenderHeight();
  66974. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66975. });
  66976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66978. this.blurHPostProcesses.push(blurX);
  66979. this.blurVPostProcesses.push(blurY);
  66980. };
  66981. // Create texture adder post-process
  66982. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66983. var _this = this;
  66984. 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);
  66985. this.textureAdderPostProcess.onApply = function (effect) {
  66986. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66987. effect.setTexture("lensSampler", _this.lensTexture);
  66988. effect.setFloat("exposure", _this.exposure);
  66989. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66990. };
  66991. // Add to pipeline
  66992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66993. };
  66994. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66995. var _this = this;
  66996. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66997. geometryRenderer.enablePosition = true;
  66998. var geometry = geometryRenderer.getGBuffer();
  66999. // Base post-process
  67000. 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));
  67001. var depthValues = BABYLON.Vector2.Zero();
  67002. this.volumetricLightPostProcess.onApply = function (effect) {
  67003. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67004. var generator = _this.sourceLight.getShadowGenerator();
  67005. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67006. effect.setTexture("positionSampler", geometry.textures[2]);
  67007. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67008. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67009. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67010. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67011. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67012. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67013. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67014. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67015. effect.setVector2("depthValues", depthValues);
  67016. }
  67017. };
  67018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67019. // Smooth
  67020. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67021. // Merge
  67022. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67023. this.volumetricLightMergePostProces.onApply = function (effect) {
  67024. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67025. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67026. };
  67027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67028. };
  67029. // Create luminance
  67030. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67031. var _this = this;
  67032. // Create luminance
  67033. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67034. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67035. var offsets = [];
  67036. this.luminancePostProcess.onApply = function (effect) {
  67037. var sU = (1.0 / _this.luminancePostProcess.width);
  67038. var sV = (1.0 / _this.luminancePostProcess.height);
  67039. offsets[0] = -0.5 * sU;
  67040. offsets[1] = 0.5 * sV;
  67041. offsets[2] = 0.5 * sU;
  67042. offsets[3] = 0.5 * sV;
  67043. offsets[4] = -0.5 * sU;
  67044. offsets[5] = -0.5 * sV;
  67045. offsets[6] = 0.5 * sU;
  67046. offsets[7] = -0.5 * sV;
  67047. effect.setArray2("lumOffsets", offsets);
  67048. };
  67049. // Add to pipeline
  67050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67051. // Create down sample luminance
  67052. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67053. var size = Math.pow(3, i);
  67054. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67055. if (i === 0) {
  67056. defines += "#define FINAL_DOWN_SAMPLER";
  67057. }
  67058. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67059. this.luminanceDownSamplePostProcesses.push(postProcess);
  67060. }
  67061. // Create callbacks and add effects
  67062. var lastLuminance = this.luminancePostProcess;
  67063. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67064. var downSampleOffsets = new Array(18);
  67065. pp.onApply = function (effect) {
  67066. if (!lastLuminance) {
  67067. return;
  67068. }
  67069. var id = 0;
  67070. for (var x = -1; x < 2; x++) {
  67071. for (var y = -1; y < 2; y++) {
  67072. downSampleOffsets[id] = x / lastLuminance.width;
  67073. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67074. id += 2;
  67075. }
  67076. }
  67077. effect.setArray2("dsOffsets", downSampleOffsets);
  67078. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67079. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67080. lastLuminance = _this.luminancePostProcess;
  67081. }
  67082. else {
  67083. lastLuminance = pp;
  67084. }
  67085. };
  67086. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67087. pp.onAfterRender = function (effect) {
  67088. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67089. 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);
  67090. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67091. };
  67092. }
  67093. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67094. });
  67095. };
  67096. // Create HDR post-process
  67097. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67098. var _this = this;
  67099. 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);
  67100. var outputLiminance = 1;
  67101. var time = 0;
  67102. var lastTime = 0;
  67103. this.hdrPostProcess.onApply = function (effect) {
  67104. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67105. time += scene.getEngine().getDeltaTime();
  67106. if (outputLiminance < 0) {
  67107. outputLiminance = _this._hdrCurrentLuminance;
  67108. }
  67109. else {
  67110. var dt = (lastTime - time) / 1000.0;
  67111. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67112. outputLiminance += _this.hdrDecreaseRate * dt;
  67113. }
  67114. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67115. outputLiminance -= _this.hdrIncreaseRate * dt;
  67116. }
  67117. else {
  67118. outputLiminance = _this._hdrCurrentLuminance;
  67119. }
  67120. }
  67121. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67122. effect.setFloat("averageLuminance", outputLiminance);
  67123. lastTime = time;
  67124. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67125. };
  67126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67127. };
  67128. // Create lens flare post-process
  67129. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67130. var _this = this;
  67131. 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);
  67132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67133. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67134. 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);
  67135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67136. var resolution = new BABYLON.Vector2(0, 0);
  67137. // Lens flare
  67138. this.lensFlarePostProcess.onApply = function (effect) {
  67139. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67140. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67141. effect.setFloat("strength", _this.lensFlareStrength);
  67142. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67143. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67144. // Shift
  67145. resolution.x = _this.lensFlarePostProcess.width;
  67146. resolution.y = _this.lensFlarePostProcess.height;
  67147. effect.setVector2("resolution", resolution);
  67148. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67149. };
  67150. // Compose
  67151. 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);
  67152. 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);
  67153. this.lensFlareComposePostProcess.onApply = function (effect) {
  67154. if (!_this._scene.activeCamera) {
  67155. return;
  67156. }
  67157. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67158. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67159. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67160. // Lens start rotation matrix
  67161. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67162. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67163. 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));
  67164. camRot *= 4.0;
  67165. 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);
  67166. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67167. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67168. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67169. };
  67170. };
  67171. // Create depth-of-field post-process
  67172. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67173. var _this = this;
  67174. 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);
  67175. this.depthOfFieldPostProcess.onApply = function (effect) {
  67176. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67177. effect.setTexture("depthSampler", _this._getDepthTexture());
  67178. effect.setFloat("distance", _this.depthOfFieldDistance);
  67179. };
  67180. // Add to pipeline
  67181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67182. };
  67183. // Create motion blur post-process
  67184. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67185. var _this = this;
  67186. 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);
  67187. var motionScale = 0;
  67188. var prevViewProjection = BABYLON.Matrix.Identity();
  67189. var invViewProjection = BABYLON.Matrix.Identity();
  67190. var viewProjection = BABYLON.Matrix.Identity();
  67191. var screenSize = BABYLON.Vector2.Zero();
  67192. this.motionBlurPostProcess.onApply = function (effect) {
  67193. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67194. viewProjection.invertToRef(invViewProjection);
  67195. effect.setMatrix("inverseViewProjection", invViewProjection);
  67196. effect.setMatrix("prevViewProjection", prevViewProjection);
  67197. prevViewProjection = viewProjection;
  67198. screenSize.x = _this.motionBlurPostProcess.width;
  67199. screenSize.y = _this.motionBlurPostProcess.height;
  67200. effect.setVector2("screenSize", screenSize);
  67201. motionScale = scene.getEngine().getFps() / 60.0;
  67202. effect.setFloat("motionScale", motionScale);
  67203. effect.setFloat("motionStrength", _this.motionStrength);
  67204. effect.setTexture("depthSampler", _this._getDepthTexture());
  67205. };
  67206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67207. };
  67208. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67209. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67210. var renderer = this._scene.enableGeometryBufferRenderer();
  67211. return renderer.getGBuffer().textures[0];
  67212. }
  67213. return this._scene.enableDepthRenderer().getDepthMap();
  67214. };
  67215. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67216. for (var i = 0; i < this._cameras.length; i++) {
  67217. var camera = this._cameras[i];
  67218. if (this.originalPostProcess) {
  67219. this.originalPostProcess.dispose(camera);
  67220. }
  67221. if (this.downSampleX4PostProcess) {
  67222. this.downSampleX4PostProcess.dispose(camera);
  67223. }
  67224. if (this.brightPassPostProcess) {
  67225. this.brightPassPostProcess.dispose(camera);
  67226. }
  67227. if (this.textureAdderPostProcess) {
  67228. this.textureAdderPostProcess.dispose(camera);
  67229. }
  67230. if (this.textureAdderFinalPostProcess) {
  67231. this.textureAdderFinalPostProcess.dispose(camera);
  67232. }
  67233. if (this.volumetricLightPostProcess) {
  67234. this.volumetricLightPostProcess.dispose(camera);
  67235. }
  67236. if (this.volumetricLightSmoothXPostProcess) {
  67237. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67238. }
  67239. if (this.volumetricLightSmoothYPostProcess) {
  67240. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67241. }
  67242. if (this.volumetricLightMergePostProces) {
  67243. this.volumetricLightMergePostProces.dispose(camera);
  67244. }
  67245. if (this.volumetricLightFinalPostProcess) {
  67246. this.volumetricLightFinalPostProcess.dispose(camera);
  67247. }
  67248. if (this.lensFlarePostProcess) {
  67249. this.lensFlarePostProcess.dispose(camera);
  67250. }
  67251. if (this.lensFlareComposePostProcess) {
  67252. this.lensFlareComposePostProcess.dispose(camera);
  67253. }
  67254. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67255. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67256. }
  67257. if (this.luminancePostProcess) {
  67258. this.luminancePostProcess.dispose(camera);
  67259. }
  67260. if (this.hdrPostProcess) {
  67261. this.hdrPostProcess.dispose(camera);
  67262. }
  67263. if (this.hdrFinalPostProcess) {
  67264. this.hdrFinalPostProcess.dispose(camera);
  67265. }
  67266. if (this.depthOfFieldPostProcess) {
  67267. this.depthOfFieldPostProcess.dispose(camera);
  67268. }
  67269. if (this.motionBlurPostProcess) {
  67270. this.motionBlurPostProcess.dispose(camera);
  67271. }
  67272. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67273. this.blurHPostProcesses[j].dispose(camera);
  67274. }
  67275. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67276. this.blurVPostProcesses[j].dispose(camera);
  67277. }
  67278. }
  67279. this.originalPostProcess = null;
  67280. this.downSampleX4PostProcess = null;
  67281. this.brightPassPostProcess = null;
  67282. this.textureAdderPostProcess = null;
  67283. this.textureAdderFinalPostProcess = null;
  67284. this.volumetricLightPostProcess = null;
  67285. this.volumetricLightSmoothXPostProcess = null;
  67286. this.volumetricLightSmoothYPostProcess = null;
  67287. this.volumetricLightMergePostProces = null;
  67288. this.volumetricLightFinalPostProcess = null;
  67289. this.lensFlarePostProcess = null;
  67290. this.lensFlareComposePostProcess = null;
  67291. this.luminancePostProcess = null;
  67292. this.hdrPostProcess = null;
  67293. this.hdrFinalPostProcess = null;
  67294. this.depthOfFieldPostProcess = null;
  67295. this.motionBlurPostProcess = null;
  67296. this.luminanceDownSamplePostProcesses = [];
  67297. this.blurHPostProcesses = [];
  67298. this.blurVPostProcesses = [];
  67299. };
  67300. // Dispose
  67301. StandardRenderingPipeline.prototype.dispose = function () {
  67302. this._disposePostProcesses();
  67303. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67304. _super.prototype.dispose.call(this);
  67305. };
  67306. // Serialize rendering pipeline
  67307. StandardRenderingPipeline.prototype.serialize = function () {
  67308. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67309. serializationObject.customType = "StandardRenderingPipeline";
  67310. return serializationObject;
  67311. };
  67312. /**
  67313. * Static members
  67314. */
  67315. // Parse serialized pipeline
  67316. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67317. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67318. };
  67319. // Luminance steps
  67320. StandardRenderingPipeline.LuminanceSteps = 6;
  67321. __decorate([
  67322. BABYLON.serialize()
  67323. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67324. __decorate([
  67325. BABYLON.serialize()
  67326. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67327. __decorate([
  67328. BABYLON.serialize()
  67329. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67330. __decorate([
  67331. BABYLON.serialize()
  67332. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67333. __decorate([
  67334. BABYLON.serializeAsTexture("lensTexture")
  67335. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67336. __decorate([
  67337. BABYLON.serialize()
  67338. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67339. __decorate([
  67340. BABYLON.serialize()
  67341. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67342. __decorate([
  67343. BABYLON.serialize()
  67344. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67345. __decorate([
  67346. BABYLON.serialize()
  67347. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67348. __decorate([
  67349. BABYLON.serialize()
  67350. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67351. __decorate([
  67352. BABYLON.serialize()
  67353. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67354. __decorate([
  67355. BABYLON.serializeAsTexture("lensColorTexture")
  67356. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67357. __decorate([
  67358. BABYLON.serialize()
  67359. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67360. __decorate([
  67361. BABYLON.serialize()
  67362. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67363. __decorate([
  67364. BABYLON.serialize()
  67365. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67366. __decorate([
  67367. BABYLON.serialize()
  67368. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67369. __decorate([
  67370. BABYLON.serializeAsTexture("lensStarTexture")
  67371. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67372. __decorate([
  67373. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67374. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67375. __decorate([
  67376. BABYLON.serialize()
  67377. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67378. __decorate([
  67379. BABYLON.serialize()
  67380. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67381. __decorate([
  67382. BABYLON.serialize()
  67383. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67384. __decorate([
  67385. BABYLON.serialize()
  67386. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67387. __decorate([
  67388. BABYLON.serialize()
  67389. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67390. __decorate([
  67391. BABYLON.serialize()
  67392. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67393. __decorate([
  67394. BABYLON.serialize()
  67395. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67396. __decorate([
  67397. BABYLON.serialize()
  67398. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67399. __decorate([
  67400. BABYLON.serialize()
  67401. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67402. __decorate([
  67403. BABYLON.serialize()
  67404. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67405. __decorate([
  67406. BABYLON.serialize()
  67407. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67408. __decorate([
  67409. BABYLON.serialize()
  67410. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67411. return StandardRenderingPipeline;
  67412. }(BABYLON.PostProcessRenderPipeline));
  67413. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67414. })(BABYLON || (BABYLON = {}));
  67415. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67416. var BABYLON;
  67417. (function (BABYLON) {
  67418. var FxaaPostProcess = /** @class */ (function (_super) {
  67419. __extends(FxaaPostProcess, _super);
  67420. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67421. if (camera === void 0) { camera = null; }
  67422. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67423. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67424. _this.onApplyObservable.add(function (effect) {
  67425. var texelSize = _this.texelSize;
  67426. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67427. });
  67428. return _this;
  67429. }
  67430. return FxaaPostProcess;
  67431. }(BABYLON.PostProcess));
  67432. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67433. })(BABYLON || (BABYLON = {}));
  67434. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67435. var BABYLON;
  67436. (function (BABYLON) {
  67437. /**
  67438. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67439. */
  67440. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67441. __extends(CircleOfConfusionPostProcess, _super);
  67442. /**
  67443. * Creates a new instance of @see CircleOfConfusionPostProcess
  67444. * @param name The name of the effect.
  67445. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67446. * @param options The required width/height ratio to downsize to before computing the render pass.
  67447. * @param camera The camera to apply the render pass to.
  67448. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67449. * @param engine The engine which the post process will be applied. (default: current engine)
  67450. * @param reusable If the post process can be reused on the same frame. (default: false)
  67451. * @param textureType Type of textures used when performing the post process. (default: 0)
  67452. */
  67453. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67454. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67455. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67456. /**
  67457. * 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.
  67458. */
  67459. _this.lensSize = 50;
  67460. /**
  67461. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67462. */
  67463. _this.fStop = 1.4;
  67464. /**
  67465. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67466. */
  67467. _this.focusDistance = 2000;
  67468. /**
  67469. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67470. */
  67471. _this.focalLength = 50;
  67472. _this.onApplyObservable.add(function (effect) {
  67473. effect.setTexture("depthSampler", depthTexture);
  67474. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67475. var aperture = _this.lensSize / _this.fStop;
  67476. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67477. effect.setFloat('focusDistance', _this.focusDistance);
  67478. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67479. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67480. });
  67481. return _this;
  67482. }
  67483. return CircleOfConfusionPostProcess;
  67484. }(BABYLON.PostProcess));
  67485. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67486. })(BABYLON || (BABYLON = {}));
  67487. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67488. var BABYLON;
  67489. (function (BABYLON) {
  67490. /**
  67491. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67492. */
  67493. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67494. __extends(DepthOfFieldMergePostProcess, _super);
  67495. /**
  67496. * Creates a new instance of @see CircleOfConfusionPostProcess
  67497. * @param name The name of the effect.
  67498. * @param original The non-blurred image to be modified
  67499. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67500. * @param blurSteps Incrimental bluring post processes.
  67501. * @param options The required width/height ratio to downsize to before computing the render pass.
  67502. * @param camera The camera to apply the render pass to.
  67503. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67504. * @param engine The engine which the post process will be applied. (default: current engine)
  67505. * @param reusable If the post process can be reused on the same frame. (default: false)
  67506. * @param textureType Type of textures used when performing the post process. (default: 0)
  67507. */
  67508. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67509. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67510. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67511. _this.onApplyObservable.add(function (effect) {
  67512. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67513. effect.setTextureFromPostProcess("originalSampler", original);
  67514. blurSteps.forEach(function (step, index) {
  67515. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67516. });
  67517. });
  67518. return _this;
  67519. }
  67520. return DepthOfFieldMergePostProcess;
  67521. }(BABYLON.PostProcess));
  67522. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67523. })(BABYLON || (BABYLON = {}));
  67524. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67525. var BABYLON;
  67526. (function (BABYLON) {
  67527. /**
  67528. * Specifies the level of max blur that should be applied when using the depth of field effect
  67529. */
  67530. var DepthOfFieldEffectBlurLevel;
  67531. (function (DepthOfFieldEffectBlurLevel) {
  67532. /**
  67533. * Subtle blur
  67534. */
  67535. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67536. /**
  67537. * Medium blur
  67538. */
  67539. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67540. /**
  67541. * Large blur
  67542. */
  67543. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67544. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67545. ;
  67546. /**
  67547. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67548. */
  67549. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67550. __extends(DepthOfFieldEffect, _super);
  67551. /**
  67552. * Creates a new instance of @see DepthOfFieldEffect
  67553. * @param scene The scene the effect belongs to.
  67554. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67555. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67556. */
  67557. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67558. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67559. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67560. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67561. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67562. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67563. // Capture circle of confusion texture
  67564. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67565. _this._depthOfFieldPass.autoClear = false;
  67566. // 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)
  67567. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67568. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67569. _this._depthOfFieldBlurY = [];
  67570. _this._depthOfFieldBlurX = [];
  67571. var blurCount = 1;
  67572. var kernelSize = 15;
  67573. switch (blurLevel) {
  67574. case DepthOfFieldEffectBlurLevel.High: {
  67575. blurCount = 3;
  67576. kernelSize = 51;
  67577. break;
  67578. }
  67579. case DepthOfFieldEffectBlurLevel.Medium: {
  67580. blurCount = 2;
  67581. kernelSize = 31;
  67582. break;
  67583. }
  67584. default: {
  67585. kernelSize = 15;
  67586. blurCount = 1;
  67587. break;
  67588. }
  67589. }
  67590. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67591. for (var i = 0; i < blurCount; i++) {
  67592. 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);
  67593. blurY.autoClear = false;
  67594. 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);
  67595. blurX.autoClear = false;
  67596. _this._depthOfFieldBlurY.push(blurY);
  67597. _this._depthOfFieldBlurX.push(blurX);
  67598. }
  67599. // Merge blurred images with original image based on circleOfConfusion
  67600. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67601. _this._depthOfFieldMerge.autoClear = false;
  67602. // Set all post processes on the effect.
  67603. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67604. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67605. effects.push(_this._depthOfFieldBlurY[i]);
  67606. effects.push(_this._depthOfFieldBlurX[i]);
  67607. }
  67608. effects.push(_this._depthOfFieldMerge);
  67609. return effects;
  67610. }, true) || this;
  67611. return _this;
  67612. }
  67613. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67614. get: function () {
  67615. return this._circleOfConfusion.focalLength;
  67616. },
  67617. /**
  67618. * The focal the length of the camera used in the effect
  67619. */
  67620. set: function (value) {
  67621. this._circleOfConfusion.focalLength = value;
  67622. },
  67623. enumerable: true,
  67624. configurable: true
  67625. });
  67626. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67627. get: function () {
  67628. return this._circleOfConfusion.fStop;
  67629. },
  67630. /**
  67631. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67632. */
  67633. set: function (value) {
  67634. this._circleOfConfusion.fStop = value;
  67635. },
  67636. enumerable: true,
  67637. configurable: true
  67638. });
  67639. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67640. get: function () {
  67641. return this._circleOfConfusion.focusDistance;
  67642. },
  67643. /**
  67644. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67645. */
  67646. set: function (value) {
  67647. this._circleOfConfusion.focusDistance = value;
  67648. },
  67649. enumerable: true,
  67650. configurable: true
  67651. });
  67652. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67653. get: function () {
  67654. return this._circleOfConfusion.lensSize;
  67655. },
  67656. /**
  67657. * 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.
  67658. */
  67659. set: function (value) {
  67660. this._circleOfConfusion.lensSize = value;
  67661. },
  67662. enumerable: true,
  67663. configurable: true
  67664. });
  67665. /**
  67666. * Disposes each of the internal effects for a given camera.
  67667. * @param camera The camera to dispose the effect on.
  67668. */
  67669. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67670. this._depthOfFieldPass.dispose(camera);
  67671. this._circleOfConfusion.dispose(camera);
  67672. this._depthOfFieldBlurX.forEach(function (element) {
  67673. element.dispose(camera);
  67674. });
  67675. this._depthOfFieldBlurY.forEach(function (element) {
  67676. element.dispose(camera);
  67677. });
  67678. this._depthOfFieldMerge.dispose(camera);
  67679. };
  67680. return DepthOfFieldEffect;
  67681. }(BABYLON.PostProcessRenderEffect));
  67682. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67683. })(BABYLON || (BABYLON = {}));
  67684. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67685. var BABYLON;
  67686. (function (BABYLON) {
  67687. /**
  67688. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67689. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67690. */
  67691. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67692. __extends(DefaultRenderingPipeline, _super);
  67693. /**
  67694. * @constructor
  67695. * @param {string} name - The rendering pipeline name
  67696. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67697. * @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)
  67698. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67699. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67700. */
  67701. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67702. if (automaticBuild === void 0) { automaticBuild = true; }
  67703. var _this = _super.call(this, scene.getEngine(), name) || this;
  67704. /**
  67705. * ID of the sharpen post process,
  67706. */
  67707. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67708. /**
  67709. * ID of the pass post process used for bloom,
  67710. */
  67711. _this.PassPostProcessId = "PassPostProcessEffect";
  67712. /**
  67713. * ID of the highlight post process used for bloom,
  67714. */
  67715. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67716. /**
  67717. * ID of the blurX post process used for bloom,
  67718. */
  67719. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67720. /**
  67721. * ID of the blurY post process used for bloom,
  67722. */
  67723. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67724. /**
  67725. * ID of the copy back post process used for bloom,
  67726. */
  67727. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67728. /**
  67729. * ID of the image processing post process;
  67730. */
  67731. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67732. /**
  67733. * ID of the Fast Approximate Anti-Aliasing post process;
  67734. */
  67735. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67736. /**
  67737. * ID of the final merge post process;
  67738. */
  67739. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67740. /**
  67741. * Animations which can be used to tweak settings over a period of time
  67742. */
  67743. _this.animations = [];
  67744. // Values
  67745. _this._sharpenEnabled = false;
  67746. _this._bloomEnabled = false;
  67747. _this._depthOfFieldEnabled = false;
  67748. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67749. _this._fxaaEnabled = false;
  67750. _this._msaaEnabled = false;
  67751. _this._imageProcessingEnabled = true;
  67752. _this._bloomScale = 0.6;
  67753. _this._buildAllowed = true;
  67754. /**
  67755. * Specifies the size of the bloom blur kernel, relative to the final output size
  67756. */
  67757. _this.bloomKernel = 64;
  67758. /**
  67759. * Specifies the weight of the bloom in the final rendering
  67760. */
  67761. _this._bloomWeight = 0.15;
  67762. _this._cameras = cameras || [];
  67763. _this._buildAllowed = automaticBuild;
  67764. // Initialize
  67765. _this._scene = scene;
  67766. var caps = _this._scene.getEngine().getCaps();
  67767. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67768. // Misc
  67769. if (_this._hdr) {
  67770. if (caps.textureHalfFloatRender) {
  67771. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67772. }
  67773. else if (caps.textureFloatRender) {
  67774. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67775. }
  67776. }
  67777. else {
  67778. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67779. }
  67780. // Attach
  67781. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67782. _this._buildPipeline();
  67783. return _this;
  67784. }
  67785. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  67786. get: function () {
  67787. return this._sharpenEnabled;
  67788. },
  67789. /**
  67790. * Enable or disable the sharpen process from the pipeline
  67791. */
  67792. set: function (enabled) {
  67793. if (this._sharpenEnabled === enabled) {
  67794. return;
  67795. }
  67796. this._sharpenEnabled = enabled;
  67797. this._buildPipeline();
  67798. },
  67799. enumerable: true,
  67800. configurable: true
  67801. });
  67802. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67803. get: function () {
  67804. return this._bloomWeight;
  67805. },
  67806. /**
  67807. * The strength of the bloom.
  67808. */
  67809. set: function (value) {
  67810. if (this._bloomWeight === value) {
  67811. return;
  67812. }
  67813. this._bloomWeight = value;
  67814. if (this._hdr && this.copyBack) {
  67815. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67816. }
  67817. },
  67818. enumerable: true,
  67819. configurable: true
  67820. });
  67821. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67822. get: function () {
  67823. return this._bloomScale;
  67824. },
  67825. /**
  67826. * The scale of the bloom, lower value will provide better performance.
  67827. */
  67828. set: function (value) {
  67829. if (this._bloomScale === value) {
  67830. return;
  67831. }
  67832. this._bloomScale = value;
  67833. this._buildPipeline();
  67834. },
  67835. enumerable: true,
  67836. configurable: true
  67837. });
  67838. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67839. get: function () {
  67840. return this._bloomEnabled;
  67841. },
  67842. /**
  67843. * Enable or disable the bloom from the pipeline
  67844. */
  67845. set: function (enabled) {
  67846. if (this._bloomEnabled === enabled) {
  67847. return;
  67848. }
  67849. this._bloomEnabled = enabled;
  67850. this._buildPipeline();
  67851. },
  67852. enumerable: true,
  67853. configurable: true
  67854. });
  67855. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67856. /**
  67857. * If the depth of field is enabled.
  67858. */
  67859. get: function () {
  67860. return this._depthOfFieldEnabled;
  67861. },
  67862. set: function (enabled) {
  67863. if (this._depthOfFieldEnabled === enabled) {
  67864. return;
  67865. }
  67866. this._depthOfFieldEnabled = enabled;
  67867. this._buildPipeline();
  67868. },
  67869. enumerable: true,
  67870. configurable: true
  67871. });
  67872. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67873. /**
  67874. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67875. */
  67876. get: function () {
  67877. return this._depthOfFieldBlurLevel;
  67878. },
  67879. set: function (value) {
  67880. if (this._depthOfFieldBlurLevel === value) {
  67881. return;
  67882. }
  67883. this._depthOfFieldBlurLevel = value;
  67884. this._buildPipeline();
  67885. },
  67886. enumerable: true,
  67887. configurable: true
  67888. });
  67889. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67890. get: function () {
  67891. return this._fxaaEnabled;
  67892. },
  67893. /**
  67894. * If the anti aliasing is enabled.
  67895. */
  67896. set: function (enabled) {
  67897. if (this._fxaaEnabled === enabled) {
  67898. return;
  67899. }
  67900. this._fxaaEnabled = enabled;
  67901. this._buildPipeline();
  67902. },
  67903. enumerable: true,
  67904. configurable: true
  67905. });
  67906. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  67907. get: function () {
  67908. return this._msaaEnabled;
  67909. },
  67910. /**
  67911. * If the multisample anti-aliasing is enabled.
  67912. */
  67913. set: function (enabled) {
  67914. if (this._msaaEnabled === enabled) {
  67915. return;
  67916. }
  67917. this._msaaEnabled = enabled;
  67918. this._buildPipeline();
  67919. },
  67920. enumerable: true,
  67921. configurable: true
  67922. });
  67923. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67924. get: function () {
  67925. return this._imageProcessingEnabled;
  67926. },
  67927. /**
  67928. * If image processing is enabled.
  67929. */
  67930. set: function (enabled) {
  67931. if (this._imageProcessingEnabled === enabled) {
  67932. return;
  67933. }
  67934. this._imageProcessingEnabled = enabled;
  67935. this._buildPipeline();
  67936. },
  67937. enumerable: true,
  67938. configurable: true
  67939. });
  67940. /**
  67941. * Force the compilation of the entire pipeline.
  67942. */
  67943. DefaultRenderingPipeline.prototype.prepare = function () {
  67944. var previousState = this._buildAllowed;
  67945. this._buildAllowed = true;
  67946. this._buildPipeline();
  67947. this._buildAllowed = previousState;
  67948. };
  67949. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67950. var _this = this;
  67951. if (!this._buildAllowed) {
  67952. return;
  67953. }
  67954. var engine = this._scene.getEngine();
  67955. this._disposePostProcesses();
  67956. this._reset();
  67957. if (this.sharpenEnabled) {
  67958. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67959. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  67960. }
  67961. if (this.depthOfFieldEnabled) {
  67962. // Enable and get current depth map
  67963. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  67964. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67965. this.addEffect(this.depthOfField);
  67966. }
  67967. if (this.bloomEnabled) {
  67968. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67969. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67970. if (!this._hdr) {
  67971. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67972. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67973. this.highlights.autoClear = false;
  67974. this.highlights.alwaysForcePOT = true;
  67975. }
  67976. 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);
  67977. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67978. this.blurX.alwaysForcePOT = true;
  67979. this.blurX.autoClear = false;
  67980. this.blurX.onActivateObservable.add(function () {
  67981. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67982. _this.blurX.kernel = _this.bloomKernel * dw;
  67983. });
  67984. 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);
  67985. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67986. this.blurY.alwaysForcePOT = true;
  67987. this.blurY.autoClear = false;
  67988. this.blurY.onActivateObservable.add(function () {
  67989. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67990. _this.blurY.kernel = _this.bloomKernel * dh;
  67991. });
  67992. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67993. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67994. this.copyBack.alwaysForcePOT = true;
  67995. if (this._hdr) {
  67996. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67997. var w = this.bloomWeight;
  67998. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67999. }
  68000. else {
  68001. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68002. }
  68003. this.copyBack.autoClear = false;
  68004. }
  68005. if (this._imageProcessingEnabled) {
  68006. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68007. if (this._hdr) {
  68008. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68009. }
  68010. else {
  68011. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68012. }
  68013. }
  68014. if (this.fxaaEnabled) {
  68015. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68016. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68017. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68018. }
  68019. else if (this._hdr && this.imageProcessing) {
  68020. this.finalMerge = this.imageProcessing;
  68021. }
  68022. else {
  68023. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68024. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68025. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68026. }
  68027. if (this.bloomEnabled) {
  68028. if (this._hdr) {
  68029. this.copyBack.shareOutputWith(this.blurX);
  68030. if (this.imageProcessing) {
  68031. this.imageProcessing.shareOutputWith(this.pass);
  68032. this.imageProcessing.autoClear = false;
  68033. }
  68034. else if (this.fxaa) {
  68035. this.fxaa.shareOutputWith(this.pass);
  68036. }
  68037. else {
  68038. this.finalMerge.shareOutputWith(this.pass);
  68039. }
  68040. }
  68041. else {
  68042. if (this.fxaa) {
  68043. this.fxaa.shareOutputWith(this.pass);
  68044. }
  68045. else {
  68046. this.finalMerge.shareOutputWith(this.pass);
  68047. }
  68048. }
  68049. }
  68050. if (this._cameras !== null) {
  68051. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68052. }
  68053. if (this.msaaEnabled) {
  68054. if (!this._enableMSAAOnFirstPostProcess()) {
  68055. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68056. }
  68057. }
  68058. };
  68059. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68060. for (var i = 0; i < this._cameras.length; i++) {
  68061. var camera = this._cameras[i];
  68062. if (this.sharpen) {
  68063. this.sharpen.dispose(camera);
  68064. }
  68065. if (this.pass) {
  68066. this.pass.dispose(camera);
  68067. }
  68068. if (this.highlights) {
  68069. this.highlights.dispose(camera);
  68070. }
  68071. if (this.blurX) {
  68072. this.blurX.dispose(camera);
  68073. }
  68074. if (this.blurY) {
  68075. this.blurY.dispose(camera);
  68076. }
  68077. if (this.copyBack) {
  68078. this.copyBack.dispose(camera);
  68079. }
  68080. if (this.imageProcessing) {
  68081. this.imageProcessing.dispose(camera);
  68082. }
  68083. if (this.fxaa) {
  68084. this.fxaa.dispose(camera);
  68085. }
  68086. if (this.finalMerge) {
  68087. this.finalMerge.dispose(camera);
  68088. }
  68089. if (this.depthOfField) {
  68090. this.depthOfField.disposeEffects(camera);
  68091. }
  68092. }
  68093. this.sharpen = null;
  68094. this.pass = null;
  68095. this.highlights = null;
  68096. this.blurX = null;
  68097. this.blurY = null;
  68098. this.copyBack = null;
  68099. this.imageProcessing = null;
  68100. this.fxaa = null;
  68101. this.finalMerge = null;
  68102. this.depthOfField = null;
  68103. };
  68104. /**
  68105. * Dispose of the pipeline and stop all post processes
  68106. */
  68107. DefaultRenderingPipeline.prototype.dispose = function () {
  68108. this._disposePostProcesses();
  68109. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68110. _super.prototype.dispose.call(this);
  68111. };
  68112. /**
  68113. * Serialize the rendering pipeline (Used when exporting)
  68114. * @returns the serialized object
  68115. */
  68116. DefaultRenderingPipeline.prototype.serialize = function () {
  68117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68118. serializationObject.customType = "DefaultRenderingPipeline";
  68119. return serializationObject;
  68120. };
  68121. /**
  68122. * Parse the serialized pipeline
  68123. * @param source Source pipeline.
  68124. * @param scene The scene to load the pipeline to.
  68125. * @param rootUrl The URL of the serialized pipeline.
  68126. * @returns An instantiated pipeline from the serialized object.
  68127. */
  68128. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68129. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68130. };
  68131. __decorate([
  68132. BABYLON.serialize()
  68133. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68134. __decorate([
  68135. BABYLON.serialize()
  68136. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68137. __decorate([
  68138. BABYLON.serialize()
  68139. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68140. __decorate([
  68141. BABYLON.serialize()
  68142. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68143. __decorate([
  68144. BABYLON.serialize()
  68145. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68146. __decorate([
  68147. BABYLON.serialize()
  68148. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68149. __decorate([
  68150. BABYLON.serialize()
  68151. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68152. __decorate([
  68153. BABYLON.serialize()
  68154. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68155. __decorate([
  68156. BABYLON.serialize()
  68157. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68158. __decorate([
  68159. BABYLON.serialize()
  68160. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68161. __decorate([
  68162. BABYLON.serialize()
  68163. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68164. __decorate([
  68165. BABYLON.serialize()
  68166. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68167. return DefaultRenderingPipeline;
  68168. }(BABYLON.PostProcessRenderPipeline));
  68169. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68170. })(BABYLON || (BABYLON = {}));
  68171. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68172. var BABYLON;
  68173. (function (BABYLON) {
  68174. /**
  68175. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68176. */
  68177. var GeometryBufferRenderer = /** @class */ (function () {
  68178. /**
  68179. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68180. * @param scene The scene the buffer belongs to
  68181. * @param ratio How big is the buffer related to the main canvas.
  68182. */
  68183. function GeometryBufferRenderer(scene, ratio) {
  68184. if (ratio === void 0) { ratio = 1; }
  68185. this._enablePosition = false;
  68186. this._scene = scene;
  68187. this._ratio = ratio;
  68188. // Render target
  68189. this._createRenderTargets();
  68190. }
  68191. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68192. /**
  68193. * Set the render list (meshes to be rendered) used in the G buffer.
  68194. */
  68195. set: function (meshes) {
  68196. this._multiRenderTarget.renderList = meshes;
  68197. },
  68198. enumerable: true,
  68199. configurable: true
  68200. });
  68201. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68202. /**
  68203. * Gets wether or not G buffer are supported by the running hardware.
  68204. * This requires draw buffer supports
  68205. */
  68206. get: function () {
  68207. return this._multiRenderTarget.isSupported;
  68208. },
  68209. enumerable: true,
  68210. configurable: true
  68211. });
  68212. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68213. /**
  68214. * Gets wether or not position are enabled for the G buffer.
  68215. */
  68216. get: function () {
  68217. return this._enablePosition;
  68218. },
  68219. /**
  68220. * Sets wether or not position are enabled for the G buffer.
  68221. */
  68222. set: function (enable) {
  68223. this._enablePosition = enable;
  68224. this.dispose();
  68225. this._createRenderTargets();
  68226. },
  68227. enumerable: true,
  68228. configurable: true
  68229. });
  68230. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68231. /**
  68232. * Gets the scene associated with the buffer.
  68233. */
  68234. get: function () {
  68235. return this._scene;
  68236. },
  68237. enumerable: true,
  68238. configurable: true
  68239. });
  68240. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68241. /**
  68242. * Gets the ratio used by the buffer during its creation.
  68243. * How big is the buffer related to the main canvas.
  68244. */
  68245. get: function () {
  68246. return this._ratio;
  68247. },
  68248. enumerable: true,
  68249. configurable: true
  68250. });
  68251. /**
  68252. * Checks wether everything is ready to render a submesh to the G buffer.
  68253. * @param subMesh the submesh to check readiness for
  68254. * @param useInstances is the mesh drawn using instance or not
  68255. * @returns true if ready otherwise false
  68256. */
  68257. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68258. var material = subMesh.getMaterial();
  68259. if (material && material.disableDepthWrite) {
  68260. return false;
  68261. }
  68262. var defines = [];
  68263. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68264. var mesh = subMesh.getMesh();
  68265. // Alpha test
  68266. if (material && material.needAlphaTesting()) {
  68267. defines.push("#define ALPHATEST");
  68268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68269. attribs.push(BABYLON.VertexBuffer.UVKind);
  68270. defines.push("#define UV1");
  68271. }
  68272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68274. defines.push("#define UV2");
  68275. }
  68276. }
  68277. // Buffers
  68278. if (this._enablePosition) {
  68279. defines.push("#define POSITION");
  68280. }
  68281. // Bones
  68282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68285. if (mesh.numBoneInfluencers > 4) {
  68286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68288. }
  68289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68290. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68291. }
  68292. else {
  68293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68294. }
  68295. // Instances
  68296. if (useInstances) {
  68297. defines.push("#define INSTANCES");
  68298. attribs.push("world0");
  68299. attribs.push("world1");
  68300. attribs.push("world2");
  68301. attribs.push("world3");
  68302. }
  68303. // Get correct effect
  68304. var join = defines.join("\n");
  68305. if (this._cachedDefines !== join) {
  68306. this._cachedDefines = join;
  68307. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68308. }
  68309. return this._effect.isReady();
  68310. };
  68311. /**
  68312. * Gets the current underlying G Buffer.
  68313. * @returns the buffer
  68314. */
  68315. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68316. return this._multiRenderTarget;
  68317. };
  68318. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68319. /**
  68320. * Gets the number of samples used to render the buffer (anti aliasing).
  68321. */
  68322. get: function () {
  68323. return this._multiRenderTarget.samples;
  68324. },
  68325. /**
  68326. * Sets the number of samples used to render the buffer (anti aliasing).
  68327. */
  68328. set: function (value) {
  68329. this._multiRenderTarget.samples = value;
  68330. },
  68331. enumerable: true,
  68332. configurable: true
  68333. });
  68334. /**
  68335. * Disposes the renderer and frees up associated resources.
  68336. */
  68337. GeometryBufferRenderer.prototype.dispose = function () {
  68338. this.getGBuffer().dispose();
  68339. };
  68340. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68341. var _this = this;
  68342. var engine = this._scene.getEngine();
  68343. var count = this._enablePosition ? 3 : 2;
  68344. 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 });
  68345. if (!this.isSupported) {
  68346. return;
  68347. }
  68348. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68349. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68350. this._multiRenderTarget.refreshRate = 1;
  68351. this._multiRenderTarget.renderParticles = false;
  68352. this._multiRenderTarget.renderList = null;
  68353. // set default depth value to 1.0 (far away)
  68354. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68355. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68356. });
  68357. // Custom render function
  68358. var renderSubMesh = function (subMesh) {
  68359. var mesh = subMesh.getRenderingMesh();
  68360. var scene = _this._scene;
  68361. var engine = scene.getEngine();
  68362. var material = subMesh.getMaterial();
  68363. if (!material) {
  68364. return;
  68365. }
  68366. // Culling
  68367. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68368. // Managing instances
  68369. var batch = mesh._getInstancesRenderList(subMesh._id);
  68370. if (batch.mustReturn) {
  68371. return;
  68372. }
  68373. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68374. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68375. engine.enableEffect(_this._effect);
  68376. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68377. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68378. _this._effect.setMatrix("view", scene.getViewMatrix());
  68379. // Alpha test
  68380. if (material && material.needAlphaTesting()) {
  68381. var alphaTexture = material.getAlphaTestTexture();
  68382. if (alphaTexture) {
  68383. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68384. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68385. }
  68386. }
  68387. // Bones
  68388. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68389. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68390. }
  68391. // Draw
  68392. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68393. }
  68394. };
  68395. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68396. var index;
  68397. if (depthOnlySubMeshes.length) {
  68398. engine.setColorWrite(false);
  68399. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68400. renderSubMesh(depthOnlySubMeshes.data[index]);
  68401. }
  68402. engine.setColorWrite(true);
  68403. }
  68404. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68405. renderSubMesh(opaqueSubMeshes.data[index]);
  68406. }
  68407. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68408. renderSubMesh(alphaTestSubMeshes.data[index]);
  68409. }
  68410. };
  68411. };
  68412. return GeometryBufferRenderer;
  68413. }());
  68414. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68415. })(BABYLON || (BABYLON = {}));
  68416. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68417. var BABYLON;
  68418. (function (BABYLON) {
  68419. var RefractionPostProcess = /** @class */ (function (_super) {
  68420. __extends(RefractionPostProcess, _super);
  68421. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68422. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68423. _this.color = color;
  68424. _this.depth = depth;
  68425. _this.colorLevel = colorLevel;
  68426. _this._ownRefractionTexture = true;
  68427. _this.onActivateObservable.add(function (cam) {
  68428. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68429. });
  68430. _this.onApplyObservable.add(function (effect) {
  68431. effect.setColor3("baseColor", _this.color);
  68432. effect.setFloat("depth", _this.depth);
  68433. effect.setFloat("colorLevel", _this.colorLevel);
  68434. effect.setTexture("refractionSampler", _this._refTexture);
  68435. });
  68436. return _this;
  68437. }
  68438. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68439. /**
  68440. * Gets or sets the refraction texture
  68441. * Please note that you are responsible for disposing the texture if you set it manually
  68442. */
  68443. get: function () {
  68444. return this._refTexture;
  68445. },
  68446. set: function (value) {
  68447. if (this._refTexture && this._ownRefractionTexture) {
  68448. this._refTexture.dispose();
  68449. }
  68450. this._refTexture = value;
  68451. this._ownRefractionTexture = false;
  68452. },
  68453. enumerable: true,
  68454. configurable: true
  68455. });
  68456. // Methods
  68457. RefractionPostProcess.prototype.dispose = function (camera) {
  68458. if (this._refTexture && this._ownRefractionTexture) {
  68459. this._refTexture.dispose();
  68460. this._refTexture = null;
  68461. }
  68462. _super.prototype.dispose.call(this, camera);
  68463. };
  68464. return RefractionPostProcess;
  68465. }(BABYLON.PostProcess));
  68466. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68467. })(BABYLON || (BABYLON = {}));
  68468. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68469. var BABYLON;
  68470. (function (BABYLON) {
  68471. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68472. __extends(BlackAndWhitePostProcess, _super);
  68473. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68474. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68475. _this.degree = 1;
  68476. _this.onApplyObservable.add(function (effect) {
  68477. effect.setFloat("degree", _this.degree);
  68478. });
  68479. return _this;
  68480. }
  68481. return BlackAndWhitePostProcess;
  68482. }(BABYLON.PostProcess));
  68483. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68484. })(BABYLON || (BABYLON = {}));
  68485. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68486. var BABYLON;
  68487. (function (BABYLON) {
  68488. /**
  68489. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68490. * input texture to perform effects such as edge detection or sharpening
  68491. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68492. */
  68493. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68494. __extends(ConvolutionPostProcess, _super);
  68495. /**
  68496. * Creates a new instance of @see ConvolutionPostProcess
  68497. * @param name The name of the effect.
  68498. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68499. * @param options The required width/height ratio to downsize to before computing the render pass.
  68500. * @param camera The camera to apply the render pass to.
  68501. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68502. * @param engine The engine which the post process will be applied. (default: current engine)
  68503. * @param reusable If the post process can be reused on the same frame. (default: false)
  68504. * @param textureType Type of textures used when performing the post process. (default: 0)
  68505. */
  68506. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68508. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68509. _this.kernel = kernel;
  68510. _this.onApply = function (effect) {
  68511. effect.setFloat2("screenSize", _this.width, _this.height);
  68512. effect.setArray("kernel", _this.kernel);
  68513. };
  68514. return _this;
  68515. }
  68516. // Statics
  68517. /**
  68518. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68519. */
  68520. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68521. /**
  68522. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68523. */
  68524. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68525. /**
  68526. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68527. */
  68528. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68529. /**
  68530. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68531. */
  68532. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68533. /**
  68534. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68535. */
  68536. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68537. /**
  68538. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68539. */
  68540. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68541. return ConvolutionPostProcess;
  68542. }(BABYLON.PostProcess));
  68543. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68544. })(BABYLON || (BABYLON = {}));
  68545. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68546. var BABYLON;
  68547. (function (BABYLON) {
  68548. /**
  68549. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68550. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68551. */
  68552. var SharpenPostProcess = /** @class */ (function (_super) {
  68553. __extends(SharpenPostProcess, _super);
  68554. /**
  68555. * Creates a new instance of @see ConvolutionPostProcess
  68556. * @param name The name of the effect.
  68557. * @param options The required width/height ratio to downsize to before computing the render pass.
  68558. * @param camera The camera to apply the render pass to.
  68559. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68560. * @param engine The engine which the post process will be applied. (default: current engine)
  68561. * @param reusable If the post process can be reused on the same frame. (default: false)
  68562. * @param textureType Type of textures used when performing the post process. (default: 0)
  68563. */
  68564. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68566. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68567. /**
  68568. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68569. */
  68570. _this.colorAmount = 1.0;
  68571. /**
  68572. * How much sharpness should be applied (default: 0.3)
  68573. */
  68574. _this.edgeAmount = 0.3;
  68575. _this.onApply = function (effect) {
  68576. effect.setFloat2("screenSize", _this.width, _this.height);
  68577. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68578. };
  68579. return _this;
  68580. }
  68581. return SharpenPostProcess;
  68582. }(BABYLON.PostProcess));
  68583. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68584. })(BABYLON || (BABYLON = {}));
  68585. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68586. var BABYLON;
  68587. (function (BABYLON) {
  68588. var FilterPostProcess = /** @class */ (function (_super) {
  68589. __extends(FilterPostProcess, _super);
  68590. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68591. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68592. _this.kernelMatrix = kernelMatrix;
  68593. _this.onApply = function (effect) {
  68594. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68595. };
  68596. return _this;
  68597. }
  68598. return FilterPostProcess;
  68599. }(BABYLON.PostProcess));
  68600. BABYLON.FilterPostProcess = FilterPostProcess;
  68601. })(BABYLON || (BABYLON = {}));
  68602. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68603. var BABYLON;
  68604. (function (BABYLON) {
  68605. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68606. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68607. __extends(VolumetricLightScatteringPostProcess, _super);
  68608. /**
  68609. * @constructor
  68610. * @param {string} name - The post-process name
  68611. * @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)
  68612. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68613. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68614. * @param {number} samples - The post-process quality, default 100
  68615. * @param {number} samplingMode - The post-process filtering mode
  68616. * @param {BABYLON.Engine} engine - The babylon engine
  68617. * @param {boolean} reusable - If the post-process is reusable
  68618. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68619. */
  68620. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68621. if (samples === void 0) { samples = 100; }
  68622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68623. 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;
  68624. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68625. /**
  68626. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68627. * @type {Vector3}
  68628. */
  68629. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68630. /**
  68631. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68632. * @type {boolean}
  68633. */
  68634. _this.useCustomMeshPosition = false;
  68635. /**
  68636. * If the post-process should inverse the light scattering direction
  68637. * @type {boolean}
  68638. */
  68639. _this.invert = true;
  68640. /**
  68641. * Array containing the excluded meshes not rendered in the internal pass
  68642. */
  68643. _this.excludedMeshes = new Array();
  68644. /**
  68645. * Controls the overall intensity of the post-process
  68646. * @type {number}
  68647. */
  68648. _this.exposure = 0.3;
  68649. /**
  68650. * Dissipates each sample's contribution in range [0, 1]
  68651. * @type {number}
  68652. */
  68653. _this.decay = 0.96815;
  68654. /**
  68655. * Controls the overall intensity of each sample
  68656. * @type {number}
  68657. */
  68658. _this.weight = 0.58767;
  68659. /**
  68660. * Controls the density of each sample
  68661. * @type {number}
  68662. */
  68663. _this.density = 0.926;
  68664. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68665. engine = scene.getEngine();
  68666. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68667. // Configure mesh
  68668. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68669. // Configure
  68670. _this._createPass(scene, ratio.passRatio || ratio);
  68671. _this.onActivate = function (camera) {
  68672. if (!_this.isSupported) {
  68673. _this.dispose(camera);
  68674. }
  68675. _this.onActivate = null;
  68676. };
  68677. _this.onApplyObservable.add(function (effect) {
  68678. _this._updateMeshScreenCoordinates(scene);
  68679. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68680. effect.setFloat("exposure", _this.exposure);
  68681. effect.setFloat("decay", _this.decay);
  68682. effect.setFloat("weight", _this.weight);
  68683. effect.setFloat("density", _this.density);
  68684. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68685. });
  68686. return _this;
  68687. }
  68688. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68689. get: function () {
  68690. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68691. return false;
  68692. },
  68693. set: function (useDiffuseColor) {
  68694. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68695. },
  68696. enumerable: true,
  68697. configurable: true
  68698. });
  68699. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68700. return "VolumetricLightScatteringPostProcess";
  68701. };
  68702. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68703. var mesh = subMesh.getMesh();
  68704. // Render this.mesh as default
  68705. if (mesh === this.mesh && mesh.material) {
  68706. return mesh.material.isReady(mesh);
  68707. }
  68708. var defines = [];
  68709. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68710. var material = subMesh.getMaterial();
  68711. // Alpha test
  68712. if (material) {
  68713. if (material.needAlphaTesting()) {
  68714. defines.push("#define ALPHATEST");
  68715. }
  68716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68717. attribs.push(BABYLON.VertexBuffer.UVKind);
  68718. defines.push("#define UV1");
  68719. }
  68720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68721. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68722. defines.push("#define UV2");
  68723. }
  68724. }
  68725. // Bones
  68726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68729. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68730. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68731. }
  68732. else {
  68733. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68734. }
  68735. // Instances
  68736. if (useInstances) {
  68737. defines.push("#define INSTANCES");
  68738. attribs.push("world0");
  68739. attribs.push("world1");
  68740. attribs.push("world2");
  68741. attribs.push("world3");
  68742. }
  68743. // Get correct effect
  68744. var join = defines.join("\n");
  68745. if (this._cachedDefines !== join) {
  68746. this._cachedDefines = join;
  68747. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68748. }
  68749. return this._volumetricLightScatteringPass.isReady();
  68750. };
  68751. /**
  68752. * Sets the new light position for light scattering effect
  68753. * @param {BABYLON.Vector3} The new custom light position
  68754. */
  68755. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68756. this.customMeshPosition = position;
  68757. };
  68758. /**
  68759. * Returns the light position for light scattering effect
  68760. * @return {BABYLON.Vector3} The custom light position
  68761. */
  68762. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68763. return this.customMeshPosition;
  68764. };
  68765. /**
  68766. * Disposes the internal assets and detaches the post-process from the camera
  68767. */
  68768. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68769. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68770. if (rttIndex !== -1) {
  68771. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68772. }
  68773. this._volumetricLightScatteringRTT.dispose();
  68774. _super.prototype.dispose.call(this, camera);
  68775. };
  68776. /**
  68777. * Returns the render target texture used by the post-process
  68778. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68779. */
  68780. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68781. return this._volumetricLightScatteringRTT;
  68782. };
  68783. // Private methods
  68784. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68785. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68786. return true;
  68787. }
  68788. return false;
  68789. };
  68790. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68791. var _this = this;
  68792. var engine = scene.getEngine();
  68793. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68794. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68795. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68796. this._volumetricLightScatteringRTT.renderList = null;
  68797. this._volumetricLightScatteringRTT.renderParticles = false;
  68798. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68799. var camera = this.getCamera();
  68800. if (camera) {
  68801. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68802. }
  68803. else {
  68804. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68805. }
  68806. // Custom render function for submeshes
  68807. var renderSubMesh = function (subMesh) {
  68808. var mesh = subMesh.getRenderingMesh();
  68809. if (_this._meshExcluded(mesh)) {
  68810. return;
  68811. }
  68812. var material = subMesh.getMaterial();
  68813. if (!material) {
  68814. return;
  68815. }
  68816. var scene = mesh.getScene();
  68817. var engine = scene.getEngine();
  68818. // Culling
  68819. engine.setState(material.backFaceCulling);
  68820. // Managing instances
  68821. var batch = mesh._getInstancesRenderList(subMesh._id);
  68822. if (batch.mustReturn) {
  68823. return;
  68824. }
  68825. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68826. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68827. var effect = _this._volumetricLightScatteringPass;
  68828. if (mesh === _this.mesh) {
  68829. if (subMesh.effect) {
  68830. effect = subMesh.effect;
  68831. }
  68832. else {
  68833. effect = material.getEffect();
  68834. }
  68835. }
  68836. engine.enableEffect(effect);
  68837. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68838. if (mesh === _this.mesh) {
  68839. material.bind(mesh.getWorldMatrix(), mesh);
  68840. }
  68841. else {
  68842. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68843. // Alpha test
  68844. if (material && material.needAlphaTesting()) {
  68845. var alphaTexture = material.getAlphaTestTexture();
  68846. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68847. if (alphaTexture) {
  68848. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68849. }
  68850. }
  68851. // Bones
  68852. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68853. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68854. }
  68855. }
  68856. // Draw
  68857. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68858. }
  68859. };
  68860. // Render target texture callbacks
  68861. var savedSceneClearColor;
  68862. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68863. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68864. savedSceneClearColor = scene.clearColor;
  68865. scene.clearColor = sceneClearColor;
  68866. });
  68867. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68868. scene.clearColor = savedSceneClearColor;
  68869. });
  68870. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68871. var engine = scene.getEngine();
  68872. var index;
  68873. if (depthOnlySubMeshes.length) {
  68874. engine.setColorWrite(false);
  68875. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68876. renderSubMesh(depthOnlySubMeshes.data[index]);
  68877. }
  68878. engine.setColorWrite(true);
  68879. }
  68880. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68881. renderSubMesh(opaqueSubMeshes.data[index]);
  68882. }
  68883. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68884. renderSubMesh(alphaTestSubMeshes.data[index]);
  68885. }
  68886. if (transparentSubMeshes.length) {
  68887. // Sort sub meshes
  68888. for (index = 0; index < transparentSubMeshes.length; index++) {
  68889. var submesh = transparentSubMeshes.data[index];
  68890. var boundingInfo = submesh.getBoundingInfo();
  68891. if (boundingInfo && scene.activeCamera) {
  68892. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68893. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68894. }
  68895. }
  68896. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68897. sortedArray.sort(function (a, b) {
  68898. // Alpha index first
  68899. if (a._alphaIndex > b._alphaIndex) {
  68900. return 1;
  68901. }
  68902. if (a._alphaIndex < b._alphaIndex) {
  68903. return -1;
  68904. }
  68905. // Then distance to camera
  68906. if (a._distanceToCamera < b._distanceToCamera) {
  68907. return 1;
  68908. }
  68909. if (a._distanceToCamera > b._distanceToCamera) {
  68910. return -1;
  68911. }
  68912. return 0;
  68913. });
  68914. // Render sub meshes
  68915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68916. for (index = 0; index < sortedArray.length; index++) {
  68917. renderSubMesh(sortedArray[index]);
  68918. }
  68919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68920. }
  68921. };
  68922. };
  68923. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68924. var transform = scene.getTransformMatrix();
  68925. var meshPosition;
  68926. if (this.useCustomMeshPosition) {
  68927. meshPosition = this.customMeshPosition;
  68928. }
  68929. else if (this.attachedNode) {
  68930. meshPosition = this.attachedNode.position;
  68931. }
  68932. else {
  68933. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68934. }
  68935. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68936. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68937. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68938. if (this.invert)
  68939. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68940. };
  68941. // Static methods
  68942. /**
  68943. * Creates a default mesh for the Volumeric Light Scattering post-process
  68944. * @param {string} The mesh name
  68945. * @param {BABYLON.Scene} The scene where to create the mesh
  68946. * @return {BABYLON.Mesh} the default mesh
  68947. */
  68948. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68949. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68950. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68951. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68952. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  68953. mesh.material = material;
  68954. return mesh;
  68955. };
  68956. __decorate([
  68957. BABYLON.serializeAsVector3()
  68958. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  68959. __decorate([
  68960. BABYLON.serialize()
  68961. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  68962. __decorate([
  68963. BABYLON.serialize()
  68964. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  68965. __decorate([
  68966. BABYLON.serializeAsMeshReference()
  68967. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68968. __decorate([
  68969. BABYLON.serialize()
  68970. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68971. __decorate([
  68972. BABYLON.serialize()
  68973. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68974. __decorate([
  68975. BABYLON.serialize()
  68976. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68977. __decorate([
  68978. BABYLON.serialize()
  68979. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68980. __decorate([
  68981. BABYLON.serialize()
  68982. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68983. return VolumetricLightScatteringPostProcess;
  68984. }(BABYLON.PostProcess));
  68985. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68986. })(BABYLON || (BABYLON = {}));
  68987. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68988. //
  68989. // This post-process allows the modification of rendered colors by using
  68990. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68991. //
  68992. // The object needs to be provided an url to a texture containing the color
  68993. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68994. // Use an image editing software to tweak the LUT to match your needs.
  68995. //
  68996. // For an example of a color LUT, see here:
  68997. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68998. // For explanations on color grading, see here:
  68999. // http://udn.epicgames.com/Three/ColorGrading.html
  69000. //
  69001. var BABYLON;
  69002. (function (BABYLON) {
  69003. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69004. __extends(ColorCorrectionPostProcess, _super);
  69005. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69006. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69007. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69008. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69009. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69010. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69011. _this.onApply = function (effect) {
  69012. effect.setTexture("colorTable", _this._colorTableTexture);
  69013. };
  69014. return _this;
  69015. }
  69016. return ColorCorrectionPostProcess;
  69017. }(BABYLON.PostProcess));
  69018. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69019. })(BABYLON || (BABYLON = {}));
  69020. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69021. var BABYLON;
  69022. (function (BABYLON) {
  69023. var TonemappingOperator;
  69024. (function (TonemappingOperator) {
  69025. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69026. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69027. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69028. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69029. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69030. ;
  69031. var TonemapPostProcess = /** @class */ (function (_super) {
  69032. __extends(TonemapPostProcess, _super);
  69033. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69035. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69036. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69037. _this._operator = _operator;
  69038. _this.exposureAdjustment = exposureAdjustment;
  69039. var defines = "#define ";
  69040. if (_this._operator === TonemappingOperator.Hable)
  69041. defines += "HABLE_TONEMAPPING";
  69042. else if (_this._operator === TonemappingOperator.Reinhard)
  69043. defines += "REINHARD_TONEMAPPING";
  69044. else if (_this._operator === TonemappingOperator.HejiDawson)
  69045. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69046. else if (_this._operator === TonemappingOperator.Photographic)
  69047. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69048. //sadly a second call to create the effect.
  69049. _this.updateEffect(defines);
  69050. _this.onApply = function (effect) {
  69051. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69052. };
  69053. return _this;
  69054. }
  69055. return TonemapPostProcess;
  69056. }(BABYLON.PostProcess));
  69057. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69058. })(BABYLON || (BABYLON = {}));
  69059. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69060. var BABYLON;
  69061. (function (BABYLON) {
  69062. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69063. __extends(DisplayPassPostProcess, _super);
  69064. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69065. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69066. }
  69067. return DisplayPassPostProcess;
  69068. }(BABYLON.PostProcess));
  69069. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69070. })(BABYLON || (BABYLON = {}));
  69071. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69072. var BABYLON;
  69073. (function (BABYLON) {
  69074. var HighlightsPostProcess = /** @class */ (function (_super) {
  69075. __extends(HighlightsPostProcess, _super);
  69076. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69078. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69079. }
  69080. return HighlightsPostProcess;
  69081. }(BABYLON.PostProcess));
  69082. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69083. })(BABYLON || (BABYLON = {}));
  69084. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69085. var BABYLON;
  69086. (function (BABYLON) {
  69087. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69088. __extends(ImageProcessingPostProcess, _super);
  69089. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69090. if (camera === void 0) { camera = null; }
  69091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69092. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69093. _this._fromLinearSpace = true;
  69094. /**
  69095. * Defines cache preventing GC.
  69096. */
  69097. _this._defines = {
  69098. IMAGEPROCESSING: false,
  69099. VIGNETTE: false,
  69100. VIGNETTEBLENDMODEMULTIPLY: false,
  69101. VIGNETTEBLENDMODEOPAQUE: false,
  69102. TONEMAPPING: false,
  69103. CONTRAST: false,
  69104. COLORCURVES: false,
  69105. COLORGRADING: false,
  69106. COLORGRADING3D: false,
  69107. FROMLINEARSPACE: false,
  69108. SAMPLER3DGREENDEPTH: false,
  69109. SAMPLER3DBGRMAP: false,
  69110. IMAGEPROCESSINGPOSTPROCESS: false,
  69111. EXPOSURE: false,
  69112. };
  69113. // Setup the configuration as forced by the constructor. This would then not force the
  69114. // scene materials output in linear space and let untouched the default forward pass.
  69115. if (imageProcessingConfiguration) {
  69116. imageProcessingConfiguration.applyByPostProcess = true;
  69117. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69118. // This will cause the shader to be compiled
  69119. _this.fromLinearSpace = false;
  69120. }
  69121. else {
  69122. _this._attachImageProcessingConfiguration(null, true);
  69123. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69124. }
  69125. _this.onApply = function (effect) {
  69126. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69127. };
  69128. return _this;
  69129. }
  69130. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69131. /**
  69132. * Gets the image processing configuration used either in this material.
  69133. */
  69134. get: function () {
  69135. return this._imageProcessingConfiguration;
  69136. },
  69137. /**
  69138. * Sets the Default image processing configuration used either in the this material.
  69139. *
  69140. * If sets to null, the scene one is in use.
  69141. */
  69142. set: function (value) {
  69143. this._attachImageProcessingConfiguration(value);
  69144. },
  69145. enumerable: true,
  69146. configurable: true
  69147. });
  69148. /**
  69149. * Attaches a new image processing configuration to the PBR Material.
  69150. * @param configuration
  69151. */
  69152. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69153. var _this = this;
  69154. if (doNotBuild === void 0) { doNotBuild = false; }
  69155. if (configuration === this._imageProcessingConfiguration) {
  69156. return;
  69157. }
  69158. // Detaches observer.
  69159. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69160. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69161. }
  69162. // Pick the scene configuration if needed.
  69163. if (!configuration) {
  69164. var scene = null;
  69165. var engine = this.getEngine();
  69166. var camera = this.getCamera();
  69167. if (camera) {
  69168. scene = camera.getScene();
  69169. }
  69170. else if (engine && engine.scenes) {
  69171. var scenes = engine.scenes;
  69172. scene = scenes[scenes.length - 1];
  69173. }
  69174. else {
  69175. scene = BABYLON.Engine.LastCreatedScene;
  69176. }
  69177. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69178. }
  69179. else {
  69180. this._imageProcessingConfiguration = configuration;
  69181. }
  69182. // Attaches observer.
  69183. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69184. _this._updateParameters();
  69185. });
  69186. // Ensure the effect will be rebuilt.
  69187. if (!doNotBuild) {
  69188. this._updateParameters();
  69189. }
  69190. };
  69191. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69192. /**
  69193. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69194. */
  69195. get: function () {
  69196. return this.imageProcessingConfiguration.colorCurves;
  69197. },
  69198. /**
  69199. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69200. */
  69201. set: function (value) {
  69202. this.imageProcessingConfiguration.colorCurves = value;
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69208. /**
  69209. * Gets wether the color curves effect is enabled.
  69210. */
  69211. get: function () {
  69212. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69213. },
  69214. /**
  69215. * Sets wether the color curves effect is enabled.
  69216. */
  69217. set: function (value) {
  69218. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69219. },
  69220. enumerable: true,
  69221. configurable: true
  69222. });
  69223. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69224. /**
  69225. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69226. */
  69227. get: function () {
  69228. return this.imageProcessingConfiguration.colorGradingTexture;
  69229. },
  69230. /**
  69231. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69232. */
  69233. set: function (value) {
  69234. this.imageProcessingConfiguration.colorGradingTexture = value;
  69235. },
  69236. enumerable: true,
  69237. configurable: true
  69238. });
  69239. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69240. /**
  69241. * Gets wether the color grading effect is enabled.
  69242. */
  69243. get: function () {
  69244. return this.imageProcessingConfiguration.colorGradingEnabled;
  69245. },
  69246. /**
  69247. * Gets wether the color grading effect is enabled.
  69248. */
  69249. set: function (value) {
  69250. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69251. },
  69252. enumerable: true,
  69253. configurable: true
  69254. });
  69255. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69256. /**
  69257. * Gets exposure used in the effect.
  69258. */
  69259. get: function () {
  69260. return this.imageProcessingConfiguration.exposure;
  69261. },
  69262. /**
  69263. * Sets exposure used in the effect.
  69264. */
  69265. set: function (value) {
  69266. this.imageProcessingConfiguration.exposure = value;
  69267. },
  69268. enumerable: true,
  69269. configurable: true
  69270. });
  69271. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69272. /**
  69273. * Gets wether tonemapping is enabled or not.
  69274. */
  69275. get: function () {
  69276. return this._imageProcessingConfiguration.toneMappingEnabled;
  69277. },
  69278. /**
  69279. * Sets wether tonemapping is enabled or not
  69280. */
  69281. set: function (value) {
  69282. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69283. },
  69284. enumerable: true,
  69285. configurable: true
  69286. });
  69287. ;
  69288. ;
  69289. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69290. /**
  69291. * Gets contrast used in the effect.
  69292. */
  69293. get: function () {
  69294. return this.imageProcessingConfiguration.contrast;
  69295. },
  69296. /**
  69297. * Sets contrast used in the effect.
  69298. */
  69299. set: function (value) {
  69300. this.imageProcessingConfiguration.contrast = value;
  69301. },
  69302. enumerable: true,
  69303. configurable: true
  69304. });
  69305. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69306. /**
  69307. * Gets Vignette stretch size.
  69308. */
  69309. get: function () {
  69310. return this.imageProcessingConfiguration.vignetteStretch;
  69311. },
  69312. /**
  69313. * Sets Vignette stretch size.
  69314. */
  69315. set: function (value) {
  69316. this.imageProcessingConfiguration.vignetteStretch = value;
  69317. },
  69318. enumerable: true,
  69319. configurable: true
  69320. });
  69321. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69322. /**
  69323. * Gets Vignette centre X Offset.
  69324. */
  69325. get: function () {
  69326. return this.imageProcessingConfiguration.vignetteCentreX;
  69327. },
  69328. /**
  69329. * Sets Vignette centre X Offset.
  69330. */
  69331. set: function (value) {
  69332. this.imageProcessingConfiguration.vignetteCentreX = value;
  69333. },
  69334. enumerable: true,
  69335. configurable: true
  69336. });
  69337. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69338. /**
  69339. * Gets Vignette centre Y Offset.
  69340. */
  69341. get: function () {
  69342. return this.imageProcessingConfiguration.vignetteCentreY;
  69343. },
  69344. /**
  69345. * Sets Vignette centre Y Offset.
  69346. */
  69347. set: function (value) {
  69348. this.imageProcessingConfiguration.vignetteCentreY = value;
  69349. },
  69350. enumerable: true,
  69351. configurable: true
  69352. });
  69353. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69354. /**
  69355. * Gets Vignette weight or intensity of the vignette effect.
  69356. */
  69357. get: function () {
  69358. return this.imageProcessingConfiguration.vignetteWeight;
  69359. },
  69360. /**
  69361. * Sets Vignette weight or intensity of the vignette effect.
  69362. */
  69363. set: function (value) {
  69364. this.imageProcessingConfiguration.vignetteWeight = value;
  69365. },
  69366. enumerable: true,
  69367. configurable: true
  69368. });
  69369. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69370. /**
  69371. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69372. * if vignetteEnabled is set to true.
  69373. */
  69374. get: function () {
  69375. return this.imageProcessingConfiguration.vignetteColor;
  69376. },
  69377. /**
  69378. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69379. * if vignetteEnabled is set to true.
  69380. */
  69381. set: function (value) {
  69382. this.imageProcessingConfiguration.vignetteColor = value;
  69383. },
  69384. enumerable: true,
  69385. configurable: true
  69386. });
  69387. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69388. /**
  69389. * Gets Camera field of view used by the Vignette effect.
  69390. */
  69391. get: function () {
  69392. return this.imageProcessingConfiguration.vignetteCameraFov;
  69393. },
  69394. /**
  69395. * Sets Camera field of view used by the Vignette effect.
  69396. */
  69397. set: function (value) {
  69398. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69404. /**
  69405. * Gets the vignette blend mode allowing different kind of effect.
  69406. */
  69407. get: function () {
  69408. return this.imageProcessingConfiguration.vignetteBlendMode;
  69409. },
  69410. /**
  69411. * Sets the vignette blend mode allowing different kind of effect.
  69412. */
  69413. set: function (value) {
  69414. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69415. },
  69416. enumerable: true,
  69417. configurable: true
  69418. });
  69419. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69420. /**
  69421. * Gets wether the vignette effect is enabled.
  69422. */
  69423. get: function () {
  69424. return this.imageProcessingConfiguration.vignetteEnabled;
  69425. },
  69426. /**
  69427. * Sets wether the vignette effect is enabled.
  69428. */
  69429. set: function (value) {
  69430. this.imageProcessingConfiguration.vignetteEnabled = value;
  69431. },
  69432. enumerable: true,
  69433. configurable: true
  69434. });
  69435. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69436. /**
  69437. * Gets wether the input of the processing is in Gamma or Linear Space.
  69438. */
  69439. get: function () {
  69440. return this._fromLinearSpace;
  69441. },
  69442. /**
  69443. * Sets wether the input of the processing is in Gamma or Linear Space.
  69444. */
  69445. set: function (value) {
  69446. if (this._fromLinearSpace === value) {
  69447. return;
  69448. }
  69449. this._fromLinearSpace = value;
  69450. this._updateParameters();
  69451. },
  69452. enumerable: true,
  69453. configurable: true
  69454. });
  69455. ImageProcessingPostProcess.prototype.getClassName = function () {
  69456. return "ImageProcessingPostProcess";
  69457. };
  69458. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69459. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69460. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69461. var defines = "";
  69462. for (var define in this._defines) {
  69463. if (this._defines[define]) {
  69464. defines += "#define " + define + ";\r\n";
  69465. }
  69466. }
  69467. var samplers = ["textureSampler"];
  69468. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69469. var uniforms = ["scale"];
  69470. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69471. this.updateEffect(defines, uniforms, samplers);
  69472. };
  69473. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69474. _super.prototype.dispose.call(this, camera);
  69475. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69476. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69477. }
  69478. this.imageProcessingConfiguration.applyByPostProcess = false;
  69479. };
  69480. __decorate([
  69481. BABYLON.serialize()
  69482. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69483. return ImageProcessingPostProcess;
  69484. }(BABYLON.PostProcess));
  69485. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69486. })(BABYLON || (BABYLON = {}));
  69487. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69488. var BABYLON;
  69489. (function (BABYLON) {
  69490. /**
  69491. * The Blur Post Process which blurs an image based on a kernel and direction.
  69492. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69493. */
  69494. var BlurPostProcess = /** @class */ (function (_super) {
  69495. __extends(BlurPostProcess, _super);
  69496. /**
  69497. * Creates a new instance of @see BlurPostProcess
  69498. * @param name The name of the effect.
  69499. * @param direction The direction in which to blur the image.
  69500. * @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.
  69501. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69502. * @param camera The camera to apply the render pass to.
  69503. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69504. * @param engine The engine which the post process will be applied. (default: current engine)
  69505. * @param reusable If the post process can be reused on the same frame. (default: false)
  69506. * @param textureType Type of textures used when performing the post process. (default: 0)
  69507. */
  69508. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69510. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69511. if (defines === void 0) { defines = ""; }
  69512. 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;
  69513. _this.direction = direction;
  69514. _this._packedFloat = false;
  69515. _this._staticDefines = "";
  69516. _this._staticDefines = defines;
  69517. _this.onApplyObservable.add(function (effect) {
  69518. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69519. });
  69520. _this.kernel = kernel;
  69521. return _this;
  69522. }
  69523. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69524. /**
  69525. * Gets the length in pixels of the blur sample region
  69526. */
  69527. get: function () {
  69528. return this._idealKernel;
  69529. },
  69530. /**
  69531. * Sets the length in pixels of the blur sample region
  69532. */
  69533. set: function (v) {
  69534. if (this._idealKernel === v) {
  69535. return;
  69536. }
  69537. v = Math.max(v, 1);
  69538. this._idealKernel = v;
  69539. this._kernel = this._nearestBestKernel(v);
  69540. this._updateParameters();
  69541. },
  69542. enumerable: true,
  69543. configurable: true
  69544. });
  69545. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69546. /**
  69547. * Gets wether or not the blur is unpacking/repacking floats
  69548. */
  69549. get: function () {
  69550. return this._packedFloat;
  69551. },
  69552. /**
  69553. * Sets wether or not the blur needs to unpack/repack floats
  69554. */
  69555. set: function (v) {
  69556. if (this._packedFloat === v) {
  69557. return;
  69558. }
  69559. this._packedFloat = v;
  69560. this._updateParameters();
  69561. },
  69562. enumerable: true,
  69563. configurable: true
  69564. });
  69565. BlurPostProcess.prototype._updateParameters = function () {
  69566. // Generate sampling offsets and weights
  69567. var N = this._kernel;
  69568. var centerIndex = (N - 1) / 2;
  69569. // Generate Gaussian sampling weights over kernel
  69570. var offsets = [];
  69571. var weights = [];
  69572. var totalWeight = 0;
  69573. for (var i = 0; i < N; i++) {
  69574. var u = i / (N - 1);
  69575. var w = this._gaussianWeight(u * 2.0 - 1);
  69576. offsets[i] = (i - centerIndex);
  69577. weights[i] = w;
  69578. totalWeight += w;
  69579. }
  69580. // Normalize weights
  69581. for (var i = 0; i < weights.length; i++) {
  69582. weights[i] /= totalWeight;
  69583. }
  69584. // Optimize: combine samples to take advantage of hardware linear sampling
  69585. // Walk from left to center, combining pairs (symmetrically)
  69586. var linearSamplingWeights = [];
  69587. var linearSamplingOffsets = [];
  69588. var linearSamplingMap = [];
  69589. for (var i = 0; i <= centerIndex; i += 2) {
  69590. var j = Math.min(i + 1, Math.floor(centerIndex));
  69591. var singleCenterSample = i === j;
  69592. if (singleCenterSample) {
  69593. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69594. }
  69595. else {
  69596. var sharedCell = j === centerIndex;
  69597. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69598. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69599. if (offsetLinear === 0) {
  69600. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69601. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69602. }
  69603. else {
  69604. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69605. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69606. }
  69607. }
  69608. }
  69609. for (var i = 0; i < linearSamplingMap.length; i++) {
  69610. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69611. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69612. }
  69613. // Replace with optimized
  69614. offsets = linearSamplingOffsets;
  69615. weights = linearSamplingWeights;
  69616. // Generate shaders
  69617. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69618. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69619. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69620. var defines = "";
  69621. defines += this._staticDefines;
  69622. for (var i = 0; i < varyingCount; i++) {
  69623. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69624. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69625. }
  69626. var depCount = 0;
  69627. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69628. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69629. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69630. depCount++;
  69631. }
  69632. if (this.packedFloat) {
  69633. defines += "#define PACKEDFLOAT 1";
  69634. }
  69635. this.updateEffect(defines, null, null, {
  69636. varyingCount: varyingCount,
  69637. depCount: depCount
  69638. });
  69639. };
  69640. /**
  69641. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69642. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69643. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69644. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69645. * The gaps between physical kernels are compensated for in the weighting of the samples
  69646. * @param idealKernel Ideal blur kernel.
  69647. * @return Nearest best kernel.
  69648. */
  69649. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69650. var v = Math.round(idealKernel);
  69651. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69652. var k = _a[_i];
  69653. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69654. return Math.max(k, 3);
  69655. }
  69656. }
  69657. return Math.max(v, 3);
  69658. };
  69659. /**
  69660. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69661. * @param x The point on the Gaussian distribution to sample.
  69662. * @return the value of the Gaussian function at x.
  69663. */
  69664. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69665. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69666. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69667. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69668. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69669. // truncated at around 1.3% of peak strength.
  69670. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69671. var sigma = (1 / 3);
  69672. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69673. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69674. var weight = (1.0 / denominator) * Math.exp(exponent);
  69675. return weight;
  69676. };
  69677. /**
  69678. * Generates a string that can be used as a floating point number in GLSL.
  69679. * @param x Value to print.
  69680. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69681. * @return GLSL float string.
  69682. */
  69683. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69684. if (decimalFigures === void 0) { decimalFigures = 8; }
  69685. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69686. };
  69687. return BlurPostProcess;
  69688. }(BABYLON.PostProcess));
  69689. BABYLON.BlurPostProcess = BlurPostProcess;
  69690. })(BABYLON || (BABYLON = {}));
  69691. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69692. var BABYLON;
  69693. (function (BABYLON) {
  69694. var Bone = /** @class */ (function (_super) {
  69695. __extends(Bone, _super);
  69696. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69697. if (parentBone === void 0) { parentBone = null; }
  69698. if (localMatrix === void 0) { localMatrix = null; }
  69699. if (restPose === void 0) { restPose = null; }
  69700. if (baseMatrix === void 0) { baseMatrix = null; }
  69701. if (index === void 0) { index = null; }
  69702. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69703. _this.name = name;
  69704. _this.children = new Array();
  69705. _this.animations = new Array();
  69706. // Set this value to map this bone to a different index in the transform matrices.
  69707. // Set this value to -1 to exclude the bone from the transform matrices.
  69708. _this._index = null;
  69709. _this._worldTransform = new BABYLON.Matrix();
  69710. _this._absoluteTransform = new BABYLON.Matrix();
  69711. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69712. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69713. _this._scaleVector = BABYLON.Vector3.One();
  69714. _this._negateScaleChildren = BABYLON.Vector3.One();
  69715. _this._scalingDeterminant = 1;
  69716. _this._skeleton = skeleton;
  69717. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69718. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69719. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69720. _this._index = index;
  69721. skeleton.bones.push(_this);
  69722. _this.setParent(parentBone, false);
  69723. _this._updateDifferenceMatrix();
  69724. return _this;
  69725. }
  69726. Object.defineProperty(Bone.prototype, "_matrix", {
  69727. get: function () {
  69728. return this._localMatrix;
  69729. },
  69730. set: function (val) {
  69731. if (this._localMatrix) {
  69732. this._localMatrix.copyFrom(val);
  69733. }
  69734. else {
  69735. this._localMatrix = val;
  69736. }
  69737. },
  69738. enumerable: true,
  69739. configurable: true
  69740. });
  69741. // Members
  69742. Bone.prototype.getSkeleton = function () {
  69743. return this._skeleton;
  69744. };
  69745. Bone.prototype.getParent = function () {
  69746. return this._parent;
  69747. };
  69748. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69749. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69750. if (this._parent === parent) {
  69751. return;
  69752. }
  69753. if (this._parent) {
  69754. var index = this._parent.children.indexOf(this);
  69755. if (index !== -1) {
  69756. this._parent.children.splice(index, 1);
  69757. }
  69758. }
  69759. this._parent = parent;
  69760. if (this._parent) {
  69761. this._parent.children.push(this);
  69762. }
  69763. if (updateDifferenceMatrix) {
  69764. this._updateDifferenceMatrix();
  69765. }
  69766. };
  69767. Bone.prototype.getLocalMatrix = function () {
  69768. return this._localMatrix;
  69769. };
  69770. Bone.prototype.getBaseMatrix = function () {
  69771. return this._baseMatrix;
  69772. };
  69773. Bone.prototype.getRestPose = function () {
  69774. return this._restPose;
  69775. };
  69776. Bone.prototype.returnToRest = function () {
  69777. this.updateMatrix(this._restPose.clone());
  69778. };
  69779. Bone.prototype.getWorldMatrix = function () {
  69780. return this._worldTransform;
  69781. };
  69782. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69783. return this._invertedAbsoluteTransform;
  69784. };
  69785. Bone.prototype.getAbsoluteTransform = function () {
  69786. return this._absoluteTransform;
  69787. };
  69788. Object.defineProperty(Bone.prototype, "position", {
  69789. // Properties (matches AbstractMesh properties)
  69790. get: function () {
  69791. return this.getPosition();
  69792. },
  69793. set: function (newPosition) {
  69794. this.setPosition(newPosition);
  69795. },
  69796. enumerable: true,
  69797. configurable: true
  69798. });
  69799. Object.defineProperty(Bone.prototype, "rotation", {
  69800. get: function () {
  69801. return this.getRotation();
  69802. },
  69803. set: function (newRotation) {
  69804. this.setRotation(newRotation);
  69805. },
  69806. enumerable: true,
  69807. configurable: true
  69808. });
  69809. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69810. get: function () {
  69811. return this.getRotationQuaternion();
  69812. },
  69813. set: function (newRotation) {
  69814. this.setRotationQuaternion(newRotation);
  69815. },
  69816. enumerable: true,
  69817. configurable: true
  69818. });
  69819. Object.defineProperty(Bone.prototype, "scaling", {
  69820. get: function () {
  69821. return this.getScale();
  69822. },
  69823. set: function (newScaling) {
  69824. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69825. },
  69826. enumerable: true,
  69827. configurable: true
  69828. });
  69829. // Methods
  69830. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69831. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69832. this._baseMatrix = matrix.clone();
  69833. this._localMatrix = matrix.clone();
  69834. this._skeleton._markAsDirty();
  69835. if (updateDifferenceMatrix) {
  69836. this._updateDifferenceMatrix();
  69837. }
  69838. };
  69839. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69840. if (!rootMatrix) {
  69841. rootMatrix = this._baseMatrix;
  69842. }
  69843. if (this._parent) {
  69844. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69845. }
  69846. else {
  69847. this._absoluteTransform.copyFrom(rootMatrix);
  69848. }
  69849. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69850. for (var index = 0; index < this.children.length; index++) {
  69851. this.children[index]._updateDifferenceMatrix();
  69852. }
  69853. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69854. };
  69855. Bone.prototype.markAsDirty = function () {
  69856. this._currentRenderId++;
  69857. this._skeleton._markAsDirty();
  69858. };
  69859. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69860. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69861. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69862. // all animation may be coming from a library skeleton, so may need to create animation
  69863. if (this.animations.length === 0) {
  69864. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69865. this.animations[0].setKeys([]);
  69866. }
  69867. // get animation info / verify there is such a range from the source bone
  69868. var sourceRange = source.animations[0].getRange(rangeName);
  69869. if (!sourceRange) {
  69870. return false;
  69871. }
  69872. var from = sourceRange.from;
  69873. var to = sourceRange.to;
  69874. var sourceKeys = source.animations[0].getKeys();
  69875. // rescaling prep
  69876. var sourceBoneLength = source.length;
  69877. var sourceParent = source.getParent();
  69878. var parent = this.getParent();
  69879. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69880. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69881. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69882. var destKeys = this.animations[0].getKeys();
  69883. // loop vars declaration
  69884. var orig;
  69885. var origTranslation;
  69886. var mat;
  69887. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69888. orig = sourceKeys[key];
  69889. if (orig.frame >= from && orig.frame <= to) {
  69890. if (rescaleAsRequired) {
  69891. mat = orig.value.clone();
  69892. // scale based on parent ratio, when bone has parent
  69893. if (parentScalingReqd) {
  69894. origTranslation = mat.getTranslation();
  69895. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69896. // scale based on skeleton dimension ratio when root bone, and value is passed
  69897. }
  69898. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69899. origTranslation = mat.getTranslation();
  69900. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69901. // use original when root bone, and no data for skelDimensionsRatio
  69902. }
  69903. else {
  69904. mat = orig.value;
  69905. }
  69906. }
  69907. else {
  69908. mat = orig.value;
  69909. }
  69910. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69911. }
  69912. }
  69913. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69914. return true;
  69915. };
  69916. /**
  69917. * Translate the bone in local or world space.
  69918. * @param vec The amount to translate the bone.
  69919. * @param space The space that the translation is in.
  69920. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69921. */
  69922. Bone.prototype.translate = function (vec, space, mesh) {
  69923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69924. var lm = this.getLocalMatrix();
  69925. if (space == BABYLON.Space.LOCAL) {
  69926. lm.m[12] += vec.x;
  69927. lm.m[13] += vec.y;
  69928. lm.m[14] += vec.z;
  69929. }
  69930. else {
  69931. var wm = null;
  69932. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69933. if (mesh) {
  69934. wm = mesh.getWorldMatrix();
  69935. }
  69936. this._skeleton.computeAbsoluteTransforms();
  69937. var tmat = Bone._tmpMats[0];
  69938. var tvec = Bone._tmpVecs[0];
  69939. if (this._parent) {
  69940. if (mesh && wm) {
  69941. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69942. tmat.multiplyToRef(wm, tmat);
  69943. }
  69944. else {
  69945. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69946. }
  69947. }
  69948. tmat.m[12] = 0;
  69949. tmat.m[13] = 0;
  69950. tmat.m[14] = 0;
  69951. tmat.invert();
  69952. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  69953. lm.m[12] += tvec.x;
  69954. lm.m[13] += tvec.y;
  69955. lm.m[14] += tvec.z;
  69956. }
  69957. this.markAsDirty();
  69958. };
  69959. /**
  69960. * Set the postion of the bone in local or world space.
  69961. * @param position The position to set the bone.
  69962. * @param space The space that the position is in.
  69963. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69964. */
  69965. Bone.prototype.setPosition = function (position, space, mesh) {
  69966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69967. var lm = this.getLocalMatrix();
  69968. if (space == BABYLON.Space.LOCAL) {
  69969. lm.m[12] = position.x;
  69970. lm.m[13] = position.y;
  69971. lm.m[14] = position.z;
  69972. }
  69973. else {
  69974. var wm = null;
  69975. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69976. if (mesh) {
  69977. wm = mesh.getWorldMatrix();
  69978. }
  69979. this._skeleton.computeAbsoluteTransforms();
  69980. var tmat = Bone._tmpMats[0];
  69981. var vec = Bone._tmpVecs[0];
  69982. if (this._parent) {
  69983. if (mesh && wm) {
  69984. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69985. tmat.multiplyToRef(wm, tmat);
  69986. }
  69987. else {
  69988. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69989. }
  69990. }
  69991. tmat.invert();
  69992. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  69993. lm.m[12] = vec.x;
  69994. lm.m[13] = vec.y;
  69995. lm.m[14] = vec.z;
  69996. }
  69997. this.markAsDirty();
  69998. };
  69999. /**
  70000. * Set the absolute postion of the bone (world space).
  70001. * @param position The position to set the bone.
  70002. * @param mesh The mesh that this bone is attached to.
  70003. */
  70004. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70005. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70006. };
  70007. /**
  70008. * Set the scale of the bone on the x, y and z axes.
  70009. * @param x The scale of the bone on the x axis.
  70010. * @param x The scale of the bone on the y axis.
  70011. * @param z The scale of the bone on the z axis.
  70012. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70013. */
  70014. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70015. if (scaleChildren === void 0) { scaleChildren = false; }
  70016. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70017. if (!scaleChildren) {
  70018. this._negateScaleChildren.x = 1 / x;
  70019. this._negateScaleChildren.y = 1 / y;
  70020. this._negateScaleChildren.z = 1 / z;
  70021. }
  70022. this._syncScaleVector();
  70023. }
  70024. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70025. };
  70026. /**
  70027. * Scale the bone on the x, y and z axes.
  70028. * @param x The amount to scale the bone on the x axis.
  70029. * @param x The amount to scale the bone on the y axis.
  70030. * @param z The amount to scale the bone on the z axis.
  70031. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70032. */
  70033. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70034. if (scaleChildren === void 0) { scaleChildren = false; }
  70035. var locMat = this.getLocalMatrix();
  70036. var origLocMat = Bone._tmpMats[0];
  70037. origLocMat.copyFrom(locMat);
  70038. var origLocMatInv = Bone._tmpMats[1];
  70039. origLocMatInv.copyFrom(origLocMat);
  70040. origLocMatInv.invert();
  70041. var scaleMat = Bone._tmpMats[2];
  70042. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70043. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70044. this._scaleVector.x *= x;
  70045. this._scaleVector.y *= y;
  70046. this._scaleVector.z *= z;
  70047. locMat.multiplyToRef(origLocMatInv, locMat);
  70048. locMat.multiplyToRef(scaleMat, locMat);
  70049. locMat.multiplyToRef(origLocMat, locMat);
  70050. var parent = this.getParent();
  70051. if (parent) {
  70052. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70053. }
  70054. else {
  70055. this.getAbsoluteTransform().copyFrom(locMat);
  70056. }
  70057. var len = this.children.length;
  70058. scaleMat.invert();
  70059. for (var i = 0; i < len; i++) {
  70060. var child = this.children[i];
  70061. var cm = child.getLocalMatrix();
  70062. cm.multiplyToRef(scaleMat, cm);
  70063. var lm = child.getLocalMatrix();
  70064. lm.m[12] *= x;
  70065. lm.m[13] *= y;
  70066. lm.m[14] *= z;
  70067. }
  70068. this.computeAbsoluteTransforms();
  70069. if (scaleChildren) {
  70070. for (var i = 0; i < len; i++) {
  70071. this.children[i].scale(x, y, z, scaleChildren);
  70072. }
  70073. }
  70074. this.markAsDirty();
  70075. };
  70076. /**
  70077. * Set the yaw, pitch, and roll of the bone in local or world space.
  70078. * @param yaw The rotation of the bone on the y axis.
  70079. * @param pitch The rotation of the bone on the x axis.
  70080. * @param roll The rotation of the bone on the z axis.
  70081. * @param space The space that the axes of rotation are in.
  70082. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70083. */
  70084. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70085. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70086. var rotMat = Bone._tmpMats[0];
  70087. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70088. var rotMatInv = Bone._tmpMats[1];
  70089. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70090. rotMatInv.multiplyToRef(rotMat, rotMat);
  70091. this._rotateWithMatrix(rotMat, space, mesh);
  70092. };
  70093. /**
  70094. * Rotate the bone on an axis in local or world space.
  70095. * @param axis The axis to rotate the bone on.
  70096. * @param amount The amount to rotate the bone.
  70097. * @param space The space that the axis is in.
  70098. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70099. */
  70100. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70101. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70102. var rmat = Bone._tmpMats[0];
  70103. rmat.m[12] = 0;
  70104. rmat.m[13] = 0;
  70105. rmat.m[14] = 0;
  70106. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70107. this._rotateWithMatrix(rmat, space, mesh);
  70108. };
  70109. /**
  70110. * Set the rotation of the bone to a particular axis angle in local or world space.
  70111. * @param axis The axis to rotate the bone on.
  70112. * @param angle The angle that the bone should be rotated to.
  70113. * @param space The space that the axis is in.
  70114. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70115. */
  70116. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70118. var rotMat = Bone._tmpMats[0];
  70119. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70120. var rotMatInv = Bone._tmpMats[1];
  70121. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70122. rotMatInv.multiplyToRef(rotMat, rotMat);
  70123. this._rotateWithMatrix(rotMat, space, mesh);
  70124. };
  70125. /**
  70126. * Set the euler rotation of the bone in local of world space.
  70127. * @param rotation The euler rotation that the bone should be set to.
  70128. * @param space The space that the rotation is in.
  70129. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70130. */
  70131. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70132. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70133. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70134. };
  70135. /**
  70136. * Set the quaternion rotation of the bone in local of world space.
  70137. * @param quat The quaternion rotation that the bone should be set to.
  70138. * @param space The space that the rotation is in.
  70139. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70140. */
  70141. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70142. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70143. var rotMatInv = Bone._tmpMats[0];
  70144. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70145. var rotMat = Bone._tmpMats[1];
  70146. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70147. rotMatInv.multiplyToRef(rotMat, rotMat);
  70148. this._rotateWithMatrix(rotMat, space, mesh);
  70149. };
  70150. /**
  70151. * Set the rotation matrix of the bone in local of world space.
  70152. * @param rotMat The rotation matrix that the bone should be set to.
  70153. * @param space The space that the rotation is in.
  70154. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70155. */
  70156. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70158. var rotMatInv = Bone._tmpMats[0];
  70159. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70160. var rotMat2 = Bone._tmpMats[1];
  70161. rotMat2.copyFrom(rotMat);
  70162. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70163. this._rotateWithMatrix(rotMat2, space, mesh);
  70164. };
  70165. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70166. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70167. var lmat = this.getLocalMatrix();
  70168. var lx = lmat.m[12];
  70169. var ly = lmat.m[13];
  70170. var lz = lmat.m[14];
  70171. var parent = this.getParent();
  70172. var parentScale = Bone._tmpMats[3];
  70173. var parentScaleInv = Bone._tmpMats[4];
  70174. if (parent) {
  70175. if (space == BABYLON.Space.WORLD) {
  70176. if (mesh) {
  70177. parentScale.copyFrom(mesh.getWorldMatrix());
  70178. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70179. }
  70180. else {
  70181. parentScale.copyFrom(parent.getAbsoluteTransform());
  70182. }
  70183. }
  70184. else {
  70185. parentScale = parent._scaleMatrix;
  70186. }
  70187. parentScaleInv.copyFrom(parentScale);
  70188. parentScaleInv.invert();
  70189. lmat.multiplyToRef(parentScale, lmat);
  70190. lmat.multiplyToRef(rmat, lmat);
  70191. lmat.multiplyToRef(parentScaleInv, lmat);
  70192. }
  70193. else {
  70194. if (space == BABYLON.Space.WORLD && mesh) {
  70195. parentScale.copyFrom(mesh.getWorldMatrix());
  70196. parentScaleInv.copyFrom(parentScale);
  70197. parentScaleInv.invert();
  70198. lmat.multiplyToRef(parentScale, lmat);
  70199. lmat.multiplyToRef(rmat, lmat);
  70200. lmat.multiplyToRef(parentScaleInv, lmat);
  70201. }
  70202. else {
  70203. lmat.multiplyToRef(rmat, lmat);
  70204. }
  70205. }
  70206. lmat.m[12] = lx;
  70207. lmat.m[13] = ly;
  70208. lmat.m[14] = lz;
  70209. this.computeAbsoluteTransforms();
  70210. this.markAsDirty();
  70211. };
  70212. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70214. if (space == BABYLON.Space.WORLD) {
  70215. var scaleMatrix = Bone._tmpMats[2];
  70216. scaleMatrix.copyFrom(this._scaleMatrix);
  70217. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70218. if (mesh) {
  70219. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70220. var meshScale = Bone._tmpMats[3];
  70221. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70222. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70223. }
  70224. rotMatInv.invert();
  70225. scaleMatrix.m[0] *= this._scalingDeterminant;
  70226. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70227. }
  70228. else {
  70229. rotMatInv.copyFrom(this.getLocalMatrix());
  70230. rotMatInv.invert();
  70231. var scaleMatrix = Bone._tmpMats[2];
  70232. scaleMatrix.copyFrom(this._scaleMatrix);
  70233. if (this._parent) {
  70234. var pscaleMatrix = Bone._tmpMats[3];
  70235. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70236. pscaleMatrix.invert();
  70237. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70238. }
  70239. else {
  70240. scaleMatrix.m[0] *= this._scalingDeterminant;
  70241. }
  70242. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70243. }
  70244. };
  70245. /**
  70246. * Get the scale of the bone
  70247. * @returns the scale of the bone
  70248. */
  70249. Bone.prototype.getScale = function () {
  70250. return this._scaleVector.clone();
  70251. };
  70252. /**
  70253. * Copy the scale of the bone to a vector3.
  70254. * @param result The vector3 to copy the scale to
  70255. */
  70256. Bone.prototype.getScaleToRef = function (result) {
  70257. result.copyFrom(this._scaleVector);
  70258. };
  70259. /**
  70260. * Get the position of the bone in local or world space.
  70261. * @param space The space that the returned position is in.
  70262. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70263. * @returns The position of the bone
  70264. */
  70265. Bone.prototype.getPosition = function (space, mesh) {
  70266. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70267. if (mesh === void 0) { mesh = null; }
  70268. var pos = BABYLON.Vector3.Zero();
  70269. this.getPositionToRef(space, mesh, pos);
  70270. return pos;
  70271. };
  70272. /**
  70273. * Copy the position of the bone to a vector3 in local or world space.
  70274. * @param space The space that the returned position is in.
  70275. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70276. * @param result The vector3 to copy the position to.
  70277. */
  70278. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70279. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70280. if (space == BABYLON.Space.LOCAL) {
  70281. var lm = this.getLocalMatrix();
  70282. result.x = lm.m[12];
  70283. result.y = lm.m[13];
  70284. result.z = lm.m[14];
  70285. }
  70286. else {
  70287. var wm = null;
  70288. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70289. if (mesh) {
  70290. wm = mesh.getWorldMatrix();
  70291. }
  70292. this._skeleton.computeAbsoluteTransforms();
  70293. var tmat = Bone._tmpMats[0];
  70294. if (mesh && wm) {
  70295. tmat.copyFrom(this.getAbsoluteTransform());
  70296. tmat.multiplyToRef(wm, tmat);
  70297. }
  70298. else {
  70299. tmat = this.getAbsoluteTransform();
  70300. }
  70301. result.x = tmat.m[12];
  70302. result.y = tmat.m[13];
  70303. result.z = tmat.m[14];
  70304. }
  70305. };
  70306. /**
  70307. * Get the absolute position of the bone (world space).
  70308. * @param mesh The mesh that this bone is attached to.
  70309. * @returns The absolute position of the bone
  70310. */
  70311. Bone.prototype.getAbsolutePosition = function (mesh) {
  70312. if (mesh === void 0) { mesh = null; }
  70313. var pos = BABYLON.Vector3.Zero();
  70314. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70315. return pos;
  70316. };
  70317. /**
  70318. * Copy the absolute position of the bone (world space) to the result param.
  70319. * @param mesh The mesh that this bone is attached to.
  70320. * @param result The vector3 to copy the absolute position to.
  70321. */
  70322. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70323. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70324. };
  70325. /**
  70326. * Compute the absolute transforms of this bone and its children.
  70327. */
  70328. Bone.prototype.computeAbsoluteTransforms = function () {
  70329. if (this._parent) {
  70330. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70331. }
  70332. else {
  70333. this._absoluteTransform.copyFrom(this._localMatrix);
  70334. var poseMatrix = this._skeleton.getPoseMatrix();
  70335. if (poseMatrix) {
  70336. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70337. }
  70338. }
  70339. var children = this.children;
  70340. var len = children.length;
  70341. for (var i = 0; i < len; i++) {
  70342. children[i].computeAbsoluteTransforms();
  70343. }
  70344. };
  70345. Bone.prototype._syncScaleVector = function () {
  70346. var lm = this.getLocalMatrix();
  70347. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70348. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70349. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70350. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70351. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70352. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70353. this._scaleVector.x = xs * Math.sqrt(xsq);
  70354. this._scaleVector.y = ys * Math.sqrt(ysq);
  70355. this._scaleVector.z = zs * Math.sqrt(zsq);
  70356. if (this._parent) {
  70357. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70358. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70359. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70360. }
  70361. 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);
  70362. };
  70363. /**
  70364. * Get the world direction from an axis that is in the local space of the bone.
  70365. * @param localAxis The local direction that is used to compute the world direction.
  70366. * @param mesh The mesh that this bone is attached to.
  70367. * @returns The world direction
  70368. */
  70369. Bone.prototype.getDirection = function (localAxis, mesh) {
  70370. if (mesh === void 0) { mesh = null; }
  70371. var result = BABYLON.Vector3.Zero();
  70372. this.getDirectionToRef(localAxis, mesh, result);
  70373. return result;
  70374. };
  70375. /**
  70376. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70377. * @param localAxis The local direction that is used to compute the world direction.
  70378. * @param mesh The mesh that this bone is attached to.
  70379. * @param result The vector3 that the world direction will be copied to.
  70380. */
  70381. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70382. if (mesh === void 0) { mesh = null; }
  70383. var wm = null;
  70384. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70385. if (mesh) {
  70386. wm = mesh.getWorldMatrix();
  70387. }
  70388. this._skeleton.computeAbsoluteTransforms();
  70389. var mat = Bone._tmpMats[0];
  70390. mat.copyFrom(this.getAbsoluteTransform());
  70391. if (mesh && wm) {
  70392. mat.multiplyToRef(wm, mat);
  70393. }
  70394. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70395. result.normalize();
  70396. };
  70397. /**
  70398. * Get the euler rotation of the bone in local or world space.
  70399. * @param space The space that the rotation should be in.
  70400. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70401. * @returns The euler rotation
  70402. */
  70403. Bone.prototype.getRotation = function (space, mesh) {
  70404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70405. if (mesh === void 0) { mesh = null; }
  70406. var result = BABYLON.Vector3.Zero();
  70407. this.getRotationToRef(space, mesh, result);
  70408. return result;
  70409. };
  70410. /**
  70411. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70412. * @param space The space that the rotation should be in.
  70413. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70414. * @param result The vector3 that the rotation should be copied to.
  70415. */
  70416. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70418. if (mesh === void 0) { mesh = null; }
  70419. var quat = Bone._tmpQuat;
  70420. this.getRotationQuaternionToRef(space, mesh, quat);
  70421. quat.toEulerAnglesToRef(result);
  70422. };
  70423. /**
  70424. * Get the quaternion rotation of the bone in either local or world space.
  70425. * @param space The space that the rotation should be in.
  70426. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70427. * @returns The quaternion rotation
  70428. */
  70429. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70430. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70431. if (mesh === void 0) { mesh = null; }
  70432. var result = BABYLON.Quaternion.Identity();
  70433. this.getRotationQuaternionToRef(space, mesh, result);
  70434. return result;
  70435. };
  70436. /**
  70437. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70438. * @param space The space that the rotation should be in.
  70439. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70440. * @param result The quaternion that the rotation should be copied to.
  70441. */
  70442. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70444. if (mesh === void 0) { mesh = null; }
  70445. if (space == BABYLON.Space.LOCAL) {
  70446. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70447. }
  70448. else {
  70449. var mat = Bone._tmpMats[0];
  70450. var amat = this.getAbsoluteTransform();
  70451. if (mesh) {
  70452. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70453. }
  70454. else {
  70455. mat.copyFrom(amat);
  70456. }
  70457. mat.m[0] *= this._scalingDeterminant;
  70458. mat.m[1] *= this._scalingDeterminant;
  70459. mat.m[2] *= this._scalingDeterminant;
  70460. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70461. }
  70462. };
  70463. /**
  70464. * Get the rotation matrix of the bone in local or world space.
  70465. * @param space The space that the rotation should be in.
  70466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70467. * @returns The rotation matrix
  70468. */
  70469. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70471. var result = BABYLON.Matrix.Identity();
  70472. this.getRotationMatrixToRef(space, mesh, result);
  70473. return result;
  70474. };
  70475. /**
  70476. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70477. * @param space The space that the rotation should be in.
  70478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70479. * @param result The quaternion that the rotation should be copied to.
  70480. */
  70481. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70483. if (space == BABYLON.Space.LOCAL) {
  70484. this.getLocalMatrix().getRotationMatrixToRef(result);
  70485. }
  70486. else {
  70487. var mat = Bone._tmpMats[0];
  70488. var amat = this.getAbsoluteTransform();
  70489. if (mesh) {
  70490. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70491. }
  70492. else {
  70493. mat.copyFrom(amat);
  70494. }
  70495. mat.m[0] *= this._scalingDeterminant;
  70496. mat.m[1] *= this._scalingDeterminant;
  70497. mat.m[2] *= this._scalingDeterminant;
  70498. mat.getRotationMatrixToRef(result);
  70499. }
  70500. };
  70501. /**
  70502. * Get the world position of a point that is in the local space of the bone.
  70503. * @param position The local position
  70504. * @param mesh The mesh that this bone is attached to.
  70505. * @returns The world position
  70506. */
  70507. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70508. if (mesh === void 0) { mesh = null; }
  70509. var result = BABYLON.Vector3.Zero();
  70510. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70511. return result;
  70512. };
  70513. /**
  70514. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70515. * @param position The local position
  70516. * @param mesh The mesh that this bone is attached to.
  70517. * @param result The vector3 that the world position should be copied to.
  70518. */
  70519. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70520. if (mesh === void 0) { mesh = null; }
  70521. var wm = null;
  70522. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70523. if (mesh) {
  70524. wm = mesh.getWorldMatrix();
  70525. }
  70526. this._skeleton.computeAbsoluteTransforms();
  70527. var tmat = Bone._tmpMats[0];
  70528. if (mesh && wm) {
  70529. tmat.copyFrom(this.getAbsoluteTransform());
  70530. tmat.multiplyToRef(wm, tmat);
  70531. }
  70532. else {
  70533. tmat = this.getAbsoluteTransform();
  70534. }
  70535. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70536. };
  70537. /**
  70538. * Get the local position of a point that is in world space.
  70539. * @param position The world position
  70540. * @param mesh The mesh that this bone is attached to.
  70541. * @returns The local position
  70542. */
  70543. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70544. if (mesh === void 0) { mesh = null; }
  70545. var result = BABYLON.Vector3.Zero();
  70546. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70547. return result;
  70548. };
  70549. /**
  70550. * Get the local position of a point that is in world space and copy it to the result param.
  70551. * @param position The world position
  70552. * @param mesh The mesh that this bone is attached to.
  70553. * @param result The vector3 that the local position should be copied to.
  70554. */
  70555. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70556. if (mesh === void 0) { mesh = null; }
  70557. var wm = null;
  70558. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70559. if (mesh) {
  70560. wm = mesh.getWorldMatrix();
  70561. }
  70562. this._skeleton.computeAbsoluteTransforms();
  70563. var tmat = Bone._tmpMats[0];
  70564. tmat.copyFrom(this.getAbsoluteTransform());
  70565. if (mesh && wm) {
  70566. tmat.multiplyToRef(wm, tmat);
  70567. }
  70568. tmat.invert();
  70569. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70570. };
  70571. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70572. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70573. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70574. return Bone;
  70575. }(BABYLON.Node));
  70576. BABYLON.Bone = Bone;
  70577. })(BABYLON || (BABYLON = {}));
  70578. //# sourceMappingURL=babylon.bone.js.map
  70579. var BABYLON;
  70580. (function (BABYLON) {
  70581. var BoneIKController = /** @class */ (function () {
  70582. function BoneIKController(mesh, bone, options) {
  70583. this.targetPosition = BABYLON.Vector3.Zero();
  70584. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70585. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70586. this.poleAngle = 0;
  70587. this.slerpAmount = 1;
  70588. this._bone1Quat = BABYLON.Quaternion.Identity();
  70589. this._bone1Mat = BABYLON.Matrix.Identity();
  70590. this._bone2Ang = Math.PI;
  70591. this._maxAngle = Math.PI;
  70592. this._rightHandedSystem = false;
  70593. this._bendAxis = BABYLON.Vector3.Right();
  70594. this._slerping = false;
  70595. this._adjustRoll = 0;
  70596. this._bone2 = bone;
  70597. this._bone1 = bone.getParent();
  70598. if (!this._bone1) {
  70599. return;
  70600. }
  70601. this.mesh = mesh;
  70602. var bonePos = bone.getPosition();
  70603. if (bone.getAbsoluteTransform().determinant() > 0) {
  70604. this._rightHandedSystem = true;
  70605. this._bendAxis.x = 0;
  70606. this._bendAxis.y = 0;
  70607. this._bendAxis.z = -1;
  70608. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70609. this._adjustRoll = Math.PI * .5;
  70610. this._bendAxis.z = 1;
  70611. }
  70612. }
  70613. if (this._bone1.length) {
  70614. var boneScale1 = this._bone1.getScale();
  70615. var boneScale2 = this._bone2.getScale();
  70616. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70617. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70618. }
  70619. else if (this._bone1.children[0]) {
  70620. mesh.computeWorldMatrix(true);
  70621. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70622. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70623. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70624. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70625. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70626. }
  70627. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70628. this.maxAngle = Math.PI;
  70629. if (options) {
  70630. if (options.targetMesh) {
  70631. this.targetMesh = options.targetMesh;
  70632. this.targetMesh.computeWorldMatrix(true);
  70633. }
  70634. if (options.poleTargetMesh) {
  70635. this.poleTargetMesh = options.poleTargetMesh;
  70636. this.poleTargetMesh.computeWorldMatrix(true);
  70637. }
  70638. else if (options.poleTargetBone) {
  70639. this.poleTargetBone = options.poleTargetBone;
  70640. }
  70641. else if (this._bone1.getParent()) {
  70642. this.poleTargetBone = this._bone1.getParent();
  70643. }
  70644. if (options.poleTargetLocalOffset) {
  70645. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70646. }
  70647. if (options.poleAngle) {
  70648. this.poleAngle = options.poleAngle;
  70649. }
  70650. if (options.bendAxis) {
  70651. this._bendAxis.copyFrom(options.bendAxis);
  70652. }
  70653. if (options.maxAngle) {
  70654. this.maxAngle = options.maxAngle;
  70655. }
  70656. if (options.slerpAmount) {
  70657. this.slerpAmount = options.slerpAmount;
  70658. }
  70659. }
  70660. }
  70661. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70662. get: function () {
  70663. return this._maxAngle;
  70664. },
  70665. set: function (value) {
  70666. this._setMaxAngle(value);
  70667. },
  70668. enumerable: true,
  70669. configurable: true
  70670. });
  70671. BoneIKController.prototype._setMaxAngle = function (ang) {
  70672. if (ang < 0) {
  70673. ang = 0;
  70674. }
  70675. if (ang > Math.PI || ang == undefined) {
  70676. ang = Math.PI;
  70677. }
  70678. this._maxAngle = ang;
  70679. var a = this._bone1Length;
  70680. var b = this._bone2Length;
  70681. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70682. };
  70683. BoneIKController.prototype.update = function () {
  70684. var bone1 = this._bone1;
  70685. if (!bone1) {
  70686. return;
  70687. }
  70688. var target = this.targetPosition;
  70689. var poleTarget = this.poleTargetPosition;
  70690. var mat1 = BoneIKController._tmpMats[0];
  70691. var mat2 = BoneIKController._tmpMats[1];
  70692. if (this.targetMesh) {
  70693. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70694. }
  70695. if (this.poleTargetBone) {
  70696. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70697. }
  70698. else if (this.poleTargetMesh) {
  70699. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70700. }
  70701. var bonePos = BoneIKController._tmpVecs[0];
  70702. var zaxis = BoneIKController._tmpVecs[1];
  70703. var xaxis = BoneIKController._tmpVecs[2];
  70704. var yaxis = BoneIKController._tmpVecs[3];
  70705. var upAxis = BoneIKController._tmpVecs[4];
  70706. var _tmpQuat = BoneIKController._tmpQuat;
  70707. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70708. poleTarget.subtractToRef(bonePos, upAxis);
  70709. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70710. upAxis.y = 1;
  70711. }
  70712. else {
  70713. upAxis.normalize();
  70714. }
  70715. target.subtractToRef(bonePos, yaxis);
  70716. yaxis.normalize();
  70717. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70718. zaxis.normalize();
  70719. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70720. xaxis.normalize();
  70721. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70722. var a = this._bone1Length;
  70723. var b = this._bone2Length;
  70724. var c = BABYLON.Vector3.Distance(bonePos, target);
  70725. if (this._maxReach > 0) {
  70726. c = Math.min(this._maxReach, c);
  70727. }
  70728. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70729. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70730. if (acosa > 1) {
  70731. acosa = 1;
  70732. }
  70733. if (acosb > 1) {
  70734. acosb = 1;
  70735. }
  70736. if (acosa < -1) {
  70737. acosa = -1;
  70738. }
  70739. if (acosb < -1) {
  70740. acosb = -1;
  70741. }
  70742. var angA = Math.acos(acosa);
  70743. var angB = Math.acos(acosb);
  70744. var angC = -angA - angB;
  70745. if (this._rightHandedSystem) {
  70746. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70747. mat2.multiplyToRef(mat1, mat1);
  70748. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70749. mat2.multiplyToRef(mat1, mat1);
  70750. }
  70751. else {
  70752. var _tmpVec = BoneIKController._tmpVecs[5];
  70753. _tmpVec.copyFrom(this._bendAxis);
  70754. _tmpVec.x *= -1;
  70755. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70756. mat2.multiplyToRef(mat1, mat1);
  70757. }
  70758. if (this.poleAngle) {
  70759. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70760. mat1.multiplyToRef(mat2, mat1);
  70761. }
  70762. if (this._bone1) {
  70763. if (this.slerpAmount < 1) {
  70764. if (!this._slerping) {
  70765. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70766. }
  70767. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70768. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70769. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70770. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70771. this._slerping = true;
  70772. }
  70773. else {
  70774. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70775. this._bone1Mat.copyFrom(mat1);
  70776. this._slerping = false;
  70777. }
  70778. }
  70779. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70780. this._bone2Ang = angC;
  70781. };
  70782. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70783. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70784. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70785. return BoneIKController;
  70786. }());
  70787. BABYLON.BoneIKController = BoneIKController;
  70788. })(BABYLON || (BABYLON = {}));
  70789. //# sourceMappingURL=babylon.boneIKController.js.map
  70790. var BABYLON;
  70791. (function (BABYLON) {
  70792. var BoneLookController = /** @class */ (function () {
  70793. /**
  70794. * Create a BoneLookController
  70795. * @param mesh the mesh that the bone belongs to
  70796. * @param bone the bone that will be looking to the target
  70797. * @param target the target Vector3 to look at
  70798. * @param settings optional settings:
  70799. * - maxYaw: the maximum angle the bone will yaw to
  70800. * - minYaw: the minimum angle the bone will yaw to
  70801. * - maxPitch: the maximum angle the bone will pitch to
  70802. * - minPitch: the minimum angle the bone will yaw to
  70803. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70804. * - upAxis: the up axis of the coordinate system
  70805. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70806. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70807. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70808. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70809. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70810. * - adjustRoll: used to make an adjustment to the roll of the bone
  70811. **/
  70812. function BoneLookController(mesh, bone, target, options) {
  70813. /**
  70814. * The up axis of the coordinate system that is used when the bone is rotated.
  70815. */
  70816. this.upAxis = BABYLON.Vector3.Up();
  70817. /**
  70818. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70819. */
  70820. this.upAxisSpace = BABYLON.Space.LOCAL;
  70821. /**
  70822. * Used to make an adjustment to the yaw of the bone.
  70823. */
  70824. this.adjustYaw = 0;
  70825. /**
  70826. * Used to make an adjustment to the pitch of the bone.
  70827. */
  70828. this.adjustPitch = 0;
  70829. /**
  70830. * Used to make an adjustment to the roll of the bone.
  70831. */
  70832. this.adjustRoll = 0;
  70833. /**
  70834. * 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).
  70835. */
  70836. this.slerpAmount = 1;
  70837. this._boneQuat = BABYLON.Quaternion.Identity();
  70838. this._slerping = false;
  70839. this._firstFrameSkipped = false;
  70840. this._fowardAxis = BABYLON.Vector3.Forward();
  70841. this.mesh = mesh;
  70842. this.bone = bone;
  70843. this.target = target;
  70844. if (options) {
  70845. if (options.adjustYaw) {
  70846. this.adjustYaw = options.adjustYaw;
  70847. }
  70848. if (options.adjustPitch) {
  70849. this.adjustPitch = options.adjustPitch;
  70850. }
  70851. if (options.adjustRoll) {
  70852. this.adjustRoll = options.adjustRoll;
  70853. }
  70854. if (options.maxYaw != null) {
  70855. this.maxYaw = options.maxYaw;
  70856. }
  70857. else {
  70858. this.maxYaw = Math.PI;
  70859. }
  70860. if (options.minYaw != null) {
  70861. this.minYaw = options.minYaw;
  70862. }
  70863. else {
  70864. this.minYaw = -Math.PI;
  70865. }
  70866. if (options.maxPitch != null) {
  70867. this.maxPitch = options.maxPitch;
  70868. }
  70869. else {
  70870. this.maxPitch = Math.PI;
  70871. }
  70872. if (options.minPitch != null) {
  70873. this.minPitch = options.minPitch;
  70874. }
  70875. else {
  70876. this.minPitch = -Math.PI;
  70877. }
  70878. if (options.slerpAmount != null) {
  70879. this.slerpAmount = options.slerpAmount;
  70880. }
  70881. if (options.upAxis != null) {
  70882. this.upAxis = options.upAxis;
  70883. }
  70884. if (options.upAxisSpace != null) {
  70885. this.upAxisSpace = options.upAxisSpace;
  70886. }
  70887. if (options.yawAxis != null || options.pitchAxis != null) {
  70888. var newYawAxis = BABYLON.Axis.Y;
  70889. var newPitchAxis = BABYLON.Axis.X;
  70890. if (options.yawAxis != null) {
  70891. newYawAxis = options.yawAxis.clone();
  70892. newYawAxis.normalize();
  70893. }
  70894. if (options.pitchAxis != null) {
  70895. newPitchAxis = options.pitchAxis.clone();
  70896. newPitchAxis.normalize();
  70897. }
  70898. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70899. this._transformYawPitch = BABYLON.Matrix.Identity();
  70900. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70901. this._transformYawPitchInv = this._transformYawPitch.clone();
  70902. this._transformYawPitch.invert();
  70903. }
  70904. }
  70905. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70906. this.upAxisSpace = BABYLON.Space.LOCAL;
  70907. }
  70908. }
  70909. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70910. /**
  70911. * Get/set the minimum yaw angle that the bone can look to.
  70912. */
  70913. get: function () {
  70914. return this._minYaw;
  70915. },
  70916. set: function (value) {
  70917. this._minYaw = value;
  70918. this._minYawSin = Math.sin(value);
  70919. this._minYawCos = Math.cos(value);
  70920. if (this._maxYaw != null) {
  70921. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70922. this._yawRange = this._maxYaw - this._minYaw;
  70923. }
  70924. },
  70925. enumerable: true,
  70926. configurable: true
  70927. });
  70928. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70929. /**
  70930. * Get/set the maximum yaw angle that the bone can look to.
  70931. */
  70932. get: function () {
  70933. return this._maxYaw;
  70934. },
  70935. set: function (value) {
  70936. this._maxYaw = value;
  70937. this._maxYawSin = Math.sin(value);
  70938. this._maxYawCos = Math.cos(value);
  70939. if (this._minYaw != null) {
  70940. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70941. this._yawRange = this._maxYaw - this._minYaw;
  70942. }
  70943. },
  70944. enumerable: true,
  70945. configurable: true
  70946. });
  70947. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  70948. /**
  70949. * Get/set the minimum pitch angle that the bone can look to.
  70950. */
  70951. get: function () {
  70952. return this._minPitch;
  70953. },
  70954. set: function (value) {
  70955. this._minPitch = value;
  70956. this._minPitchTan = Math.tan(value);
  70957. },
  70958. enumerable: true,
  70959. configurable: true
  70960. });
  70961. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  70962. /**
  70963. * Get/set the maximum pitch angle that the bone can look to.
  70964. */
  70965. get: function () {
  70966. return this._maxPitch;
  70967. },
  70968. set: function (value) {
  70969. this._maxPitch = value;
  70970. this._maxPitchTan = Math.tan(value);
  70971. },
  70972. enumerable: true,
  70973. configurable: true
  70974. });
  70975. /**
  70976. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  70977. */
  70978. BoneLookController.prototype.update = function () {
  70979. //skip the first frame when slerping so that the mesh rotation is correct
  70980. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  70981. this._firstFrameSkipped = true;
  70982. return;
  70983. }
  70984. var bone = this.bone;
  70985. var bonePos = BoneLookController._tmpVecs[0];
  70986. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  70987. var target = this.target;
  70988. var _tmpMat1 = BoneLookController._tmpMats[0];
  70989. var _tmpMat2 = BoneLookController._tmpMats[1];
  70990. var mesh = this.mesh;
  70991. var parentBone = bone.getParent();
  70992. var upAxis = BoneLookController._tmpVecs[1];
  70993. upAxis.copyFrom(this.upAxis);
  70994. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  70995. if (this._transformYawPitch) {
  70996. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  70997. }
  70998. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  70999. }
  71000. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71001. mesh.getDirectionToRef(upAxis, upAxis);
  71002. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71003. upAxis.normalize();
  71004. }
  71005. }
  71006. var checkYaw = false;
  71007. var checkPitch = false;
  71008. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71009. checkYaw = true;
  71010. }
  71011. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71012. checkPitch = true;
  71013. }
  71014. if (checkYaw || checkPitch) {
  71015. var spaceMat = BoneLookController._tmpMats[2];
  71016. var spaceMatInv = BoneLookController._tmpMats[3];
  71017. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71018. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71019. }
  71020. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71021. spaceMat.copyFrom(mesh.getWorldMatrix());
  71022. }
  71023. else {
  71024. var forwardAxis = BoneLookController._tmpVecs[2];
  71025. forwardAxis.copyFrom(this._fowardAxis);
  71026. if (this._transformYawPitch) {
  71027. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71028. }
  71029. if (parentBone) {
  71030. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71031. }
  71032. else {
  71033. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71034. }
  71035. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71036. rightAxis.normalize();
  71037. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71038. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71039. }
  71040. spaceMat.invertToRef(spaceMatInv);
  71041. var xzlen = null;
  71042. if (checkPitch) {
  71043. var localTarget = BoneLookController._tmpVecs[3];
  71044. target.subtractToRef(bonePos, localTarget);
  71045. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71046. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71047. var pitch = Math.atan2(localTarget.y, xzlen);
  71048. var newPitch = pitch;
  71049. if (pitch > this._maxPitch) {
  71050. localTarget.y = this._maxPitchTan * xzlen;
  71051. newPitch = this._maxPitch;
  71052. }
  71053. else if (pitch < this._minPitch) {
  71054. localTarget.y = this._minPitchTan * xzlen;
  71055. newPitch = this._minPitch;
  71056. }
  71057. if (pitch != newPitch) {
  71058. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71059. localTarget.addInPlace(bonePos);
  71060. target = localTarget;
  71061. }
  71062. }
  71063. if (checkYaw) {
  71064. var localTarget = BoneLookController._tmpVecs[4];
  71065. target.subtractToRef(bonePos, localTarget);
  71066. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71067. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71068. var newYaw = yaw;
  71069. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71070. if (xzlen == null) {
  71071. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71072. }
  71073. if (this._yawRange > Math.PI) {
  71074. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71075. localTarget.z = this._maxYawCos * xzlen;
  71076. localTarget.x = this._maxYawSin * xzlen;
  71077. newYaw = this._maxYaw;
  71078. }
  71079. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71080. localTarget.z = this._minYawCos * xzlen;
  71081. localTarget.x = this._minYawSin * xzlen;
  71082. newYaw = this._minYaw;
  71083. }
  71084. }
  71085. else {
  71086. if (yaw > this._maxYaw) {
  71087. localTarget.z = this._maxYawCos * xzlen;
  71088. localTarget.x = this._maxYawSin * xzlen;
  71089. newYaw = this._maxYaw;
  71090. }
  71091. else if (yaw < this._minYaw) {
  71092. localTarget.z = this._minYawCos * xzlen;
  71093. localTarget.x = this._minYawSin * xzlen;
  71094. newYaw = this._minYaw;
  71095. }
  71096. }
  71097. }
  71098. if (this._slerping && this._yawRange > Math.PI) {
  71099. //are we going to be crossing into the min/max region?
  71100. var boneFwd = BoneLookController._tmpVecs[8];
  71101. boneFwd.copyFrom(BABYLON.Axis.Z);
  71102. if (this._transformYawPitch) {
  71103. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71104. }
  71105. var boneRotMat = BoneLookController._tmpMats[4];
  71106. this._boneQuat.toRotationMatrix(boneRotMat);
  71107. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71108. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71109. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71110. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71111. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71112. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71113. if (angBtwTar > angBtwMidYaw) {
  71114. if (xzlen == null) {
  71115. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71116. }
  71117. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71118. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71119. if (angBtwMin < angBtwMax) {
  71120. newYaw = boneYaw + Math.PI * .75;
  71121. localTarget.z = Math.cos(newYaw) * xzlen;
  71122. localTarget.x = Math.sin(newYaw) * xzlen;
  71123. }
  71124. else {
  71125. newYaw = boneYaw - Math.PI * .75;
  71126. localTarget.z = Math.cos(newYaw) * xzlen;
  71127. localTarget.x = Math.sin(newYaw) * xzlen;
  71128. }
  71129. }
  71130. }
  71131. if (yaw != newYaw) {
  71132. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71133. localTarget.addInPlace(bonePos);
  71134. target = localTarget;
  71135. }
  71136. }
  71137. }
  71138. var zaxis = BoneLookController._tmpVecs[5];
  71139. var xaxis = BoneLookController._tmpVecs[6];
  71140. var yaxis = BoneLookController._tmpVecs[7];
  71141. var _tmpQuat = BoneLookController._tmpQuat;
  71142. target.subtractToRef(bonePos, zaxis);
  71143. zaxis.normalize();
  71144. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71145. xaxis.normalize();
  71146. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71147. yaxis.normalize();
  71148. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71149. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71150. return;
  71151. }
  71152. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71153. return;
  71154. }
  71155. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71156. return;
  71157. }
  71158. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71159. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71160. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71161. }
  71162. if (this.slerpAmount < 1) {
  71163. if (!this._slerping) {
  71164. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71165. }
  71166. if (this._transformYawPitch) {
  71167. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71168. }
  71169. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71170. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71171. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71172. this._slerping = true;
  71173. }
  71174. else {
  71175. if (this._transformYawPitch) {
  71176. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71177. }
  71178. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71179. this._slerping = false;
  71180. }
  71181. };
  71182. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71183. var angDiff = ang2 - ang1;
  71184. angDiff %= Math.PI * 2;
  71185. if (angDiff > Math.PI) {
  71186. angDiff -= Math.PI * 2;
  71187. }
  71188. else if (angDiff < -Math.PI) {
  71189. angDiff += Math.PI * 2;
  71190. }
  71191. return angDiff;
  71192. };
  71193. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71194. ang1 %= (2 * Math.PI);
  71195. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71196. ang2 %= (2 * Math.PI);
  71197. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71198. var ab = 0;
  71199. if (ang1 < ang2) {
  71200. ab = ang2 - ang1;
  71201. }
  71202. else {
  71203. ab = ang1 - ang2;
  71204. }
  71205. if (ab > Math.PI) {
  71206. ab = Math.PI * 2 - ab;
  71207. }
  71208. return ab;
  71209. };
  71210. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71211. ang %= (2 * Math.PI);
  71212. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71213. ang1 %= (2 * Math.PI);
  71214. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71215. ang2 %= (2 * Math.PI);
  71216. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71217. if (ang1 < ang2) {
  71218. if (ang > ang1 && ang < ang2) {
  71219. return true;
  71220. }
  71221. }
  71222. else {
  71223. if (ang > ang2 && ang < ang1) {
  71224. return true;
  71225. }
  71226. }
  71227. return false;
  71228. };
  71229. 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()];
  71230. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71231. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71232. return BoneLookController;
  71233. }());
  71234. BABYLON.BoneLookController = BoneLookController;
  71235. })(BABYLON || (BABYLON = {}));
  71236. //# sourceMappingURL=babylon.boneLookController.js.map
  71237. var BABYLON;
  71238. (function (BABYLON) {
  71239. var Skeleton = /** @class */ (function () {
  71240. function Skeleton(name, id, scene) {
  71241. this.name = name;
  71242. this.id = id;
  71243. this.bones = new Array();
  71244. this.needInitialSkinMatrix = false;
  71245. this._isDirty = true;
  71246. this._meshesWithPoseMatrix = new Array();
  71247. this._identity = BABYLON.Matrix.Identity();
  71248. this._ranges = {};
  71249. this._lastAbsoluteTransformsUpdateId = -1;
  71250. /**
  71251. * Specifies if the skeleton should be serialized.
  71252. */
  71253. this.doNotSerialize = false;
  71254. // Events
  71255. /**
  71256. * An event triggered before computing the skeleton's matrices
  71257. * @type {BABYLON.Observable}
  71258. */
  71259. this.onBeforeComputeObservable = new BABYLON.Observable();
  71260. this.bones = [];
  71261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71262. scene.skeletons.push(this);
  71263. //make sure it will recalculate the matrix next time prepare is called.
  71264. this._isDirty = true;
  71265. }
  71266. // Members
  71267. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71268. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71269. return mesh._bonesTransformMatrices;
  71270. }
  71271. if (!this._transformMatrices) {
  71272. this.prepare();
  71273. }
  71274. return this._transformMatrices;
  71275. };
  71276. Skeleton.prototype.getScene = function () {
  71277. return this._scene;
  71278. };
  71279. // Methods
  71280. /**
  71281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71282. */
  71283. Skeleton.prototype.toString = function (fullDetails) {
  71284. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71285. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71286. if (fullDetails) {
  71287. ret += ", Ranges: {";
  71288. var first = true;
  71289. for (var name_1 in this._ranges) {
  71290. if (first) {
  71291. ret += ", ";
  71292. first = false;
  71293. }
  71294. ret += name_1;
  71295. }
  71296. ret += "}";
  71297. }
  71298. return ret;
  71299. };
  71300. /**
  71301. * Get bone's index searching by name
  71302. * @param {string} name is bone's name to search for
  71303. * @return {number} Indice of the bone. Returns -1 if not found
  71304. */
  71305. Skeleton.prototype.getBoneIndexByName = function (name) {
  71306. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71307. if (this.bones[boneIndex].name === name) {
  71308. return boneIndex;
  71309. }
  71310. }
  71311. return -1;
  71312. };
  71313. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71314. // check name not already in use
  71315. if (!this._ranges[name]) {
  71316. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71317. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71318. if (this.bones[i].animations[0]) {
  71319. this.bones[i].animations[0].createRange(name, from, to);
  71320. }
  71321. }
  71322. }
  71323. };
  71324. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71325. if (deleteFrames === void 0) { deleteFrames = true; }
  71326. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71327. if (this.bones[i].animations[0]) {
  71328. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71329. }
  71330. }
  71331. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71332. };
  71333. Skeleton.prototype.getAnimationRange = function (name) {
  71334. return this._ranges[name];
  71335. };
  71336. /**
  71337. * Returns as an Array, all AnimationRanges defined on this skeleton
  71338. */
  71339. Skeleton.prototype.getAnimationRanges = function () {
  71340. var animationRanges = [];
  71341. var name;
  71342. var i = 0;
  71343. for (name in this._ranges) {
  71344. animationRanges[i] = this._ranges[name];
  71345. i++;
  71346. }
  71347. return animationRanges;
  71348. };
  71349. /**
  71350. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71351. */
  71352. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71353. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71354. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71355. return false;
  71356. }
  71357. var ret = true;
  71358. var frameOffset = this._getHighestAnimationFrame() + 1;
  71359. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71360. var boneDict = {};
  71361. var sourceBones = source.bones;
  71362. var nBones;
  71363. var i;
  71364. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71365. boneDict[sourceBones[i].name] = sourceBones[i];
  71366. }
  71367. if (this.bones.length !== sourceBones.length) {
  71368. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71369. ret = false;
  71370. }
  71371. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71372. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71373. var boneName = this.bones[i].name;
  71374. var sourceBone = boneDict[boneName];
  71375. if (sourceBone) {
  71376. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71377. }
  71378. else {
  71379. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71380. ret = false;
  71381. }
  71382. }
  71383. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71384. var range = source.getAnimationRange(name);
  71385. if (range) {
  71386. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71387. }
  71388. return ret;
  71389. };
  71390. Skeleton.prototype.returnToRest = function () {
  71391. for (var index = 0; index < this.bones.length; index++) {
  71392. this.bones[index].returnToRest();
  71393. }
  71394. };
  71395. Skeleton.prototype._getHighestAnimationFrame = function () {
  71396. var ret = 0;
  71397. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71398. if (this.bones[i].animations[0]) {
  71399. var highest = this.bones[i].animations[0].getHighestFrame();
  71400. if (ret < highest) {
  71401. ret = highest;
  71402. }
  71403. }
  71404. }
  71405. return ret;
  71406. };
  71407. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71408. var range = this.getAnimationRange(name);
  71409. if (!range) {
  71410. return null;
  71411. }
  71412. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71413. };
  71414. Skeleton.prototype._markAsDirty = function () {
  71415. this._isDirty = true;
  71416. };
  71417. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71418. this._meshesWithPoseMatrix.push(mesh);
  71419. };
  71420. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71421. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71422. if (index > -1) {
  71423. this._meshesWithPoseMatrix.splice(index, 1);
  71424. }
  71425. };
  71426. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71427. this.onBeforeComputeObservable.notifyObservers(this);
  71428. for (var index = 0; index < this.bones.length; index++) {
  71429. var bone = this.bones[index];
  71430. var parentBone = bone.getParent();
  71431. if (parentBone) {
  71432. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71433. }
  71434. else {
  71435. if (initialSkinMatrix) {
  71436. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71437. }
  71438. else {
  71439. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71440. }
  71441. }
  71442. if (bone._index !== -1) {
  71443. var mappedIndex = bone._index === null ? index : bone._index;
  71444. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71445. }
  71446. }
  71447. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71448. };
  71449. Skeleton.prototype.prepare = function () {
  71450. if (!this._isDirty) {
  71451. return;
  71452. }
  71453. if (this.needInitialSkinMatrix) {
  71454. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71455. var mesh = this._meshesWithPoseMatrix[index];
  71456. var poseMatrix = mesh.getPoseMatrix();
  71457. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71458. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71459. }
  71460. if (this._synchronizedWithMesh !== mesh) {
  71461. this._synchronizedWithMesh = mesh;
  71462. // Prepare bones
  71463. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71464. var bone = this.bones[boneIndex];
  71465. if (!bone.getParent()) {
  71466. var matrix = bone.getBaseMatrix();
  71467. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71468. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71469. }
  71470. }
  71471. }
  71472. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71473. }
  71474. }
  71475. else {
  71476. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71477. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71478. }
  71479. this._computeTransformMatrices(this._transformMatrices, null);
  71480. }
  71481. this._isDirty = false;
  71482. this._scene._activeBones.addCount(this.bones.length, false);
  71483. };
  71484. Skeleton.prototype.getAnimatables = function () {
  71485. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71486. this._animatables = [];
  71487. for (var index = 0; index < this.bones.length; index++) {
  71488. this._animatables.push(this.bones[index]);
  71489. }
  71490. }
  71491. return this._animatables;
  71492. };
  71493. Skeleton.prototype.clone = function (name, id) {
  71494. var result = new Skeleton(name, id || name, this._scene);
  71495. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71496. for (var index = 0; index < this.bones.length; index++) {
  71497. var source = this.bones[index];
  71498. var parentBone = null;
  71499. var parent_1 = source.getParent();
  71500. if (parent_1) {
  71501. var parentIndex = this.bones.indexOf(parent_1);
  71502. parentBone = result.bones[parentIndex];
  71503. }
  71504. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71505. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71506. }
  71507. if (this._ranges) {
  71508. result._ranges = {};
  71509. for (var rangeName in this._ranges) {
  71510. var range = this._ranges[rangeName];
  71511. if (range) {
  71512. result._ranges[rangeName] = range.clone();
  71513. }
  71514. }
  71515. }
  71516. this._isDirty = true;
  71517. return result;
  71518. };
  71519. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71520. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71521. this.bones.forEach(function (bone) {
  71522. bone.animations.forEach(function (animation) {
  71523. animation.enableBlending = true;
  71524. animation.blendingSpeed = blendingSpeed;
  71525. });
  71526. });
  71527. };
  71528. Skeleton.prototype.dispose = function () {
  71529. this._meshesWithPoseMatrix = [];
  71530. // Animations
  71531. this.getScene().stopAnimation(this);
  71532. // Remove from scene
  71533. this.getScene().removeSkeleton(this);
  71534. };
  71535. Skeleton.prototype.serialize = function () {
  71536. var serializationObject = {};
  71537. serializationObject.name = this.name;
  71538. serializationObject.id = this.id;
  71539. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71540. serializationObject.bones = [];
  71541. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71542. for (var index = 0; index < this.bones.length; index++) {
  71543. var bone = this.bones[index];
  71544. var parent_2 = bone.getParent();
  71545. var serializedBone = {
  71546. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71547. name: bone.name,
  71548. matrix: bone.getBaseMatrix().toArray(),
  71549. rest: bone.getRestPose().toArray()
  71550. };
  71551. serializationObject.bones.push(serializedBone);
  71552. if (bone.length) {
  71553. serializedBone.length = bone.length;
  71554. }
  71555. if (bone.animations && bone.animations.length > 0) {
  71556. serializedBone.animation = bone.animations[0].serialize();
  71557. }
  71558. serializationObject.ranges = [];
  71559. for (var name in this._ranges) {
  71560. var source = this._ranges[name];
  71561. if (!source) {
  71562. continue;
  71563. }
  71564. var range = {};
  71565. range.name = name;
  71566. range.from = source.from;
  71567. range.to = source.to;
  71568. serializationObject.ranges.push(range);
  71569. }
  71570. }
  71571. return serializationObject;
  71572. };
  71573. Skeleton.Parse = function (parsedSkeleton, scene) {
  71574. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71575. if (parsedSkeleton.dimensionsAtRest) {
  71576. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71577. }
  71578. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71579. var index;
  71580. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71581. var parsedBone = parsedSkeleton.bones[index];
  71582. var parentBone = null;
  71583. if (parsedBone.parentBoneIndex > -1) {
  71584. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71585. }
  71586. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71587. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71588. if (parsedBone.length) {
  71589. bone.length = parsedBone.length;
  71590. }
  71591. if (parsedBone.animation) {
  71592. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71593. }
  71594. }
  71595. // placed after bones, so createAnimationRange can cascade down
  71596. if (parsedSkeleton.ranges) {
  71597. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71598. var data = parsedSkeleton.ranges[index];
  71599. skeleton.createAnimationRange(data.name, data.from, data.to);
  71600. }
  71601. }
  71602. return skeleton;
  71603. };
  71604. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71605. if (forceUpdate === void 0) { forceUpdate = false; }
  71606. var renderId = this._scene.getRenderId();
  71607. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71608. this.bones[0].computeAbsoluteTransforms();
  71609. this._lastAbsoluteTransformsUpdateId = renderId;
  71610. }
  71611. };
  71612. Skeleton.prototype.getPoseMatrix = function () {
  71613. var poseMatrix = null;
  71614. if (this._meshesWithPoseMatrix.length > 0) {
  71615. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71616. }
  71617. return poseMatrix;
  71618. };
  71619. Skeleton.prototype.sortBones = function () {
  71620. var bones = new Array();
  71621. var visited = new Array(this.bones.length);
  71622. for (var index = 0; index < this.bones.length; index++) {
  71623. this._sortBones(index, bones, visited);
  71624. }
  71625. this.bones = bones;
  71626. };
  71627. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71628. if (visited[index]) {
  71629. return;
  71630. }
  71631. visited[index] = true;
  71632. var bone = this.bones[index];
  71633. if (bone._index === undefined) {
  71634. bone._index = index;
  71635. }
  71636. var parentBone = bone.getParent();
  71637. if (parentBone) {
  71638. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71639. }
  71640. bones.push(bone);
  71641. };
  71642. return Skeleton;
  71643. }());
  71644. BABYLON.Skeleton = Skeleton;
  71645. })(BABYLON || (BABYLON = {}));
  71646. //# sourceMappingURL=babylon.skeleton.js.map
  71647. var BABYLON;
  71648. (function (BABYLON) {
  71649. var SphericalPolynomial = /** @class */ (function () {
  71650. function SphericalPolynomial() {
  71651. this.x = BABYLON.Vector3.Zero();
  71652. this.y = BABYLON.Vector3.Zero();
  71653. this.z = BABYLON.Vector3.Zero();
  71654. this.xx = BABYLON.Vector3.Zero();
  71655. this.yy = BABYLON.Vector3.Zero();
  71656. this.zz = BABYLON.Vector3.Zero();
  71657. this.xy = BABYLON.Vector3.Zero();
  71658. this.yz = BABYLON.Vector3.Zero();
  71659. this.zx = BABYLON.Vector3.Zero();
  71660. }
  71661. SphericalPolynomial.prototype.addAmbient = function (color) {
  71662. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71663. this.xx = this.xx.add(colorVector);
  71664. this.yy = this.yy.add(colorVector);
  71665. this.zz = this.zz.add(colorVector);
  71666. };
  71667. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71668. var result = new SphericalPolynomial();
  71669. result.x = harmonics.L11.scale(1.02333);
  71670. result.y = harmonics.L1_1.scale(1.02333);
  71671. result.z = harmonics.L10.scale(1.02333);
  71672. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71673. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71674. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71675. result.yz = harmonics.L2_1.scale(0.858086);
  71676. result.zx = harmonics.L21.scale(0.858086);
  71677. result.xy = harmonics.L2_2.scale(0.858086);
  71678. result.scale(1.0 / Math.PI);
  71679. return result;
  71680. };
  71681. SphericalPolynomial.prototype.scale = function (scale) {
  71682. this.x = this.x.scale(scale);
  71683. this.y = this.y.scale(scale);
  71684. this.z = this.z.scale(scale);
  71685. this.xx = this.xx.scale(scale);
  71686. this.yy = this.yy.scale(scale);
  71687. this.zz = this.zz.scale(scale);
  71688. this.yz = this.yz.scale(scale);
  71689. this.zx = this.zx.scale(scale);
  71690. this.xy = this.xy.scale(scale);
  71691. };
  71692. return SphericalPolynomial;
  71693. }());
  71694. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71695. var SphericalHarmonics = /** @class */ (function () {
  71696. function SphericalHarmonics() {
  71697. this.L00 = BABYLON.Vector3.Zero();
  71698. this.L1_1 = BABYLON.Vector3.Zero();
  71699. this.L10 = BABYLON.Vector3.Zero();
  71700. this.L11 = BABYLON.Vector3.Zero();
  71701. this.L2_2 = BABYLON.Vector3.Zero();
  71702. this.L2_1 = BABYLON.Vector3.Zero();
  71703. this.L20 = BABYLON.Vector3.Zero();
  71704. this.L21 = BABYLON.Vector3.Zero();
  71705. this.L22 = BABYLON.Vector3.Zero();
  71706. }
  71707. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71708. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71709. var c = colorVector.scale(deltaSolidAngle);
  71710. this.L00 = this.L00.add(c.scale(0.282095));
  71711. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71712. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71713. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71714. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71715. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71716. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71717. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71718. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71719. };
  71720. SphericalHarmonics.prototype.scale = function (scale) {
  71721. this.L00 = this.L00.scale(scale);
  71722. this.L1_1 = this.L1_1.scale(scale);
  71723. this.L10 = this.L10.scale(scale);
  71724. this.L11 = this.L11.scale(scale);
  71725. this.L2_2 = this.L2_2.scale(scale);
  71726. this.L2_1 = this.L2_1.scale(scale);
  71727. this.L20 = this.L20.scale(scale);
  71728. this.L21 = this.L21.scale(scale);
  71729. this.L22 = this.L22.scale(scale);
  71730. };
  71731. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71732. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71733. //
  71734. // E_lm = A_l * L_lm
  71735. //
  71736. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71737. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71738. // the scaling factors are given in equation 9.
  71739. // Constant (Band 0)
  71740. this.L00 = this.L00.scale(3.141593);
  71741. // Linear (Band 1)
  71742. this.L1_1 = this.L1_1.scale(2.094395);
  71743. this.L10 = this.L10.scale(2.094395);
  71744. this.L11 = this.L11.scale(2.094395);
  71745. // Quadratic (Band 2)
  71746. this.L2_2 = this.L2_2.scale(0.785398);
  71747. this.L2_1 = this.L2_1.scale(0.785398);
  71748. this.L20 = this.L20.scale(0.785398);
  71749. this.L21 = this.L21.scale(0.785398);
  71750. this.L22 = this.L22.scale(0.785398);
  71751. };
  71752. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71753. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71754. // L = (1/pi) * E * rho
  71755. //
  71756. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71757. this.scale(1.0 / Math.PI);
  71758. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71759. // (The pixel shader must apply albedo after texture fetches, etc).
  71760. };
  71761. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71762. var result = new SphericalHarmonics();
  71763. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71764. result.L1_1 = polynomial.y.scale(0.977204);
  71765. result.L10 = polynomial.z.scale(0.977204);
  71766. result.L11 = polynomial.x.scale(0.977204);
  71767. result.L2_2 = polynomial.xy.scale(1.16538);
  71768. result.L2_1 = polynomial.yz.scale(1.16538);
  71769. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71770. result.L21 = polynomial.zx.scale(1.16538);
  71771. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71772. result.scale(Math.PI);
  71773. return result;
  71774. };
  71775. return SphericalHarmonics;
  71776. }());
  71777. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71778. })(BABYLON || (BABYLON = {}));
  71779. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71780. var BABYLON;
  71781. (function (BABYLON) {
  71782. var FileFaceOrientation = /** @class */ (function () {
  71783. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71784. this.name = name;
  71785. this.worldAxisForNormal = worldAxisForNormal;
  71786. this.worldAxisForFileX = worldAxisForFileX;
  71787. this.worldAxisForFileY = worldAxisForFileY;
  71788. }
  71789. return FileFaceOrientation;
  71790. }());
  71791. ;
  71792. /**
  71793. * Helper class dealing with the extraction of spherical polynomial dataArray
  71794. * from a cube map.
  71795. */
  71796. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71797. function CubeMapToSphericalPolynomialTools() {
  71798. }
  71799. /**
  71800. * Converts a texture to the according Spherical Polynomial data.
  71801. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71802. *
  71803. * @param texture The texture to extract the information from.
  71804. * @return The Spherical Polynomial data.
  71805. */
  71806. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71807. if (!texture.isCube) {
  71808. // Only supports cube Textures currently.
  71809. return null;
  71810. }
  71811. var size = texture.getSize().width;
  71812. var right = texture.readPixels(0);
  71813. var left = texture.readPixels(1);
  71814. var up;
  71815. var down;
  71816. if (texture.isRenderTarget) {
  71817. up = texture.readPixels(3);
  71818. down = texture.readPixels(2);
  71819. }
  71820. else {
  71821. up = texture.readPixels(2);
  71822. down = texture.readPixels(3);
  71823. }
  71824. var front = texture.readPixels(4);
  71825. var back = texture.readPixels(5);
  71826. var gammaSpace = texture.gammaSpace;
  71827. // Always read as RGBA.
  71828. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71829. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71830. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71831. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71832. }
  71833. var cubeInfo = {
  71834. size: size,
  71835. right: right,
  71836. left: left,
  71837. up: up,
  71838. down: down,
  71839. front: front,
  71840. back: back,
  71841. format: format,
  71842. type: type,
  71843. gammaSpace: gammaSpace,
  71844. };
  71845. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71846. };
  71847. /**
  71848. * Converts a cubemap to the according Spherical Polynomial data.
  71849. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71850. *
  71851. * @param cubeInfo The Cube map to extract the information from.
  71852. * @return The Spherical Polynomial data.
  71853. */
  71854. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71855. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71856. var totalSolidAngle = 0.0;
  71857. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71858. var du = 2.0 / cubeInfo.size;
  71859. var dv = du;
  71860. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71861. var minUV = du * 0.5 - 1.0;
  71862. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71863. var fileFace = this.FileFaces[faceIndex];
  71864. var dataArray = cubeInfo[fileFace.name];
  71865. var v = minUV;
  71866. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71867. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71868. // Because SP is still linear, so summation is fine in that basis.
  71869. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71870. for (var y = 0; y < cubeInfo.size; y++) {
  71871. var u = minUV;
  71872. for (var x = 0; x < cubeInfo.size; x++) {
  71873. // World direction (not normalised)
  71874. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71875. worldDirection.normalize();
  71876. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71877. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71878. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71879. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71880. // Handle Integer types.
  71881. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71882. r /= 255;
  71883. g /= 255;
  71884. b /= 255;
  71885. }
  71886. // Handle Gamma space textures.
  71887. if (cubeInfo.gammaSpace) {
  71888. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71889. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71890. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71891. }
  71892. var color = new BABYLON.Color3(r, g, b);
  71893. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71894. totalSolidAngle += deltaSolidAngle;
  71895. u += du;
  71896. }
  71897. v += dv;
  71898. }
  71899. }
  71900. // Solid angle for entire sphere is 4*pi
  71901. var sphereSolidAngle = 4.0 * Math.PI;
  71902. // Adjust the solid angle to allow for how many faces we processed.
  71903. var facesProcessed = 6.0;
  71904. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71905. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71906. // This is needed because the numerical integration over the cube uses a
  71907. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71908. // and also to compensate for accumulative error due to float precision in the summation.
  71909. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71910. sphericalHarmonics.scale(correctionFactor);
  71911. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71912. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71913. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71914. };
  71915. CubeMapToSphericalPolynomialTools.FileFaces = [
  71916. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71917. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71918. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71919. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71920. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71921. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71922. ];
  71923. return CubeMapToSphericalPolynomialTools;
  71924. }());
  71925. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71926. })(BABYLON || (BABYLON = {}));
  71927. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71928. var BABYLON;
  71929. (function (BABYLON) {
  71930. /**
  71931. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71932. */
  71933. var PanoramaToCubeMapTools = /** @class */ (function () {
  71934. function PanoramaToCubeMapTools() {
  71935. }
  71936. /**
  71937. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71938. *
  71939. * @param float32Array The source data.
  71940. * @param inputWidth The width of the input panorama.
  71941. * @param inputhHeight The height of the input panorama.
  71942. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  71943. * @return The cubemap data
  71944. */
  71945. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  71946. if (!float32Array) {
  71947. throw "ConvertPanoramaToCubemap: input cannot be null";
  71948. }
  71949. if (float32Array.length != inputWidth * inputHeight * 3) {
  71950. throw "ConvertPanoramaToCubemap: input size is wrong";
  71951. }
  71952. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  71953. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  71954. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  71955. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  71956. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  71957. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  71958. return {
  71959. front: textureFront,
  71960. back: textureBack,
  71961. left: textureLeft,
  71962. right: textureRight,
  71963. up: textureUp,
  71964. down: textureDown,
  71965. size: size,
  71966. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  71967. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  71968. gammaSpace: false,
  71969. };
  71970. };
  71971. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  71972. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  71973. var textureArray = new Float32Array(buffer);
  71974. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  71975. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  71976. var dy = 1 / texSize;
  71977. var fy = 0;
  71978. for (var y = 0; y < texSize; y++) {
  71979. var xv1 = faceData[0];
  71980. var xv2 = faceData[2];
  71981. for (var x = 0; x < texSize; x++) {
  71982. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  71983. v.normalize();
  71984. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  71985. // 3 channels per pixels
  71986. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  71987. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  71988. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  71989. xv1 = xv1.add(rotDX1);
  71990. xv2 = xv2.add(rotDX2);
  71991. }
  71992. fy += dy;
  71993. }
  71994. return textureArray;
  71995. };
  71996. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  71997. var theta = Math.atan2(vDir.z, vDir.x);
  71998. var phi = Math.acos(vDir.y);
  71999. while (theta < -Math.PI)
  72000. theta += 2 * Math.PI;
  72001. while (theta > Math.PI)
  72002. theta -= 2 * Math.PI;
  72003. var dx = theta / Math.PI;
  72004. var dy = phi / Math.PI;
  72005. // recenter.
  72006. dx = dx * 0.5 + 0.5;
  72007. var px = Math.round(dx * inputWidth);
  72008. if (px < 0)
  72009. px = 0;
  72010. else if (px >= inputWidth)
  72011. px = inputWidth - 1;
  72012. var py = Math.round(dy * inputHeight);
  72013. if (py < 0)
  72014. py = 0;
  72015. else if (py >= inputHeight)
  72016. py = inputHeight - 1;
  72017. var inputY = (inputHeight - py - 1);
  72018. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72019. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72020. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72021. return {
  72022. r: r,
  72023. g: g,
  72024. b: b
  72025. };
  72026. };
  72027. PanoramaToCubeMapTools.FACE_FRONT = [
  72028. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72029. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72030. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72031. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72032. ];
  72033. PanoramaToCubeMapTools.FACE_BACK = [
  72034. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72035. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72036. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72037. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72038. ];
  72039. PanoramaToCubeMapTools.FACE_RIGHT = [
  72040. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72041. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72042. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72043. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72044. ];
  72045. PanoramaToCubeMapTools.FACE_LEFT = [
  72046. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72047. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72048. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72049. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72050. ];
  72051. PanoramaToCubeMapTools.FACE_DOWN = [
  72052. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72053. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72054. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72055. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72056. ];
  72057. PanoramaToCubeMapTools.FACE_UP = [
  72058. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72059. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72060. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72061. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72062. ];
  72063. return PanoramaToCubeMapTools;
  72064. }());
  72065. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72066. })(BABYLON || (BABYLON = {}));
  72067. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72068. var BABYLON;
  72069. (function (BABYLON) {
  72070. ;
  72071. /**
  72072. * This groups tools to convert HDR texture to native colors array.
  72073. */
  72074. var HDRTools = /** @class */ (function () {
  72075. function HDRTools() {
  72076. }
  72077. HDRTools.Ldexp = function (mantissa, exponent) {
  72078. if (exponent > 1023) {
  72079. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72080. }
  72081. if (exponent < -1074) {
  72082. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72083. }
  72084. return mantissa * Math.pow(2, exponent);
  72085. };
  72086. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72087. if (exponent > 0) {
  72088. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72089. float32array[index + 0] = red * exponent;
  72090. float32array[index + 1] = green * exponent;
  72091. float32array[index + 2] = blue * exponent;
  72092. }
  72093. else {
  72094. float32array[index + 0] = 0;
  72095. float32array[index + 1] = 0;
  72096. float32array[index + 2] = 0;
  72097. }
  72098. };
  72099. HDRTools.readStringLine = function (uint8array, startIndex) {
  72100. var line = "";
  72101. var character = "";
  72102. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72103. character = String.fromCharCode(uint8array[i]);
  72104. if (character == "\n") {
  72105. break;
  72106. }
  72107. line += character;
  72108. }
  72109. return line;
  72110. };
  72111. /**
  72112. * Reads header information from an RGBE texture stored in a native array.
  72113. * More information on this format are available here:
  72114. * https://en.wikipedia.org/wiki/RGBE_image_format
  72115. *
  72116. * @param uint8array The binary file stored in native array.
  72117. * @return The header information.
  72118. */
  72119. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72120. var height = 0;
  72121. var width = 0;
  72122. var line = this.readStringLine(uint8array, 0);
  72123. if (line[0] != '#' || line[1] != '?') {
  72124. throw "Bad HDR Format.";
  72125. }
  72126. var endOfHeader = false;
  72127. var findFormat = false;
  72128. var lineIndex = 0;
  72129. do {
  72130. lineIndex += (line.length + 1);
  72131. line = this.readStringLine(uint8array, lineIndex);
  72132. if (line == "FORMAT=32-bit_rle_rgbe") {
  72133. findFormat = true;
  72134. }
  72135. else if (line.length == 0) {
  72136. endOfHeader = true;
  72137. }
  72138. } while (!endOfHeader);
  72139. if (!findFormat) {
  72140. throw "HDR Bad header format, unsupported FORMAT";
  72141. }
  72142. lineIndex += (line.length + 1);
  72143. line = this.readStringLine(uint8array, lineIndex);
  72144. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72145. var match = sizeRegexp.exec(line);
  72146. // TODO. Support +Y and -X if needed.
  72147. if (!match || match.length < 3) {
  72148. throw "HDR Bad header format, no size";
  72149. }
  72150. width = parseInt(match[2]);
  72151. height = parseInt(match[1]);
  72152. if (width < 8 || width > 0x7fff) {
  72153. throw "HDR Bad header format, unsupported size";
  72154. }
  72155. lineIndex += (line.length + 1);
  72156. return {
  72157. height: height,
  72158. width: width,
  72159. dataPosition: lineIndex
  72160. };
  72161. };
  72162. /**
  72163. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72164. * This RGBE texture needs to store the information as a panorama.
  72165. *
  72166. * More information on this format are available here:
  72167. * https://en.wikipedia.org/wiki/RGBE_image_format
  72168. *
  72169. * @param buffer The binary file stored in an array buffer.
  72170. * @param size The expected size of the extracted cubemap.
  72171. * @return The Cube Map information.
  72172. */
  72173. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72174. var uint8array = new Uint8Array(buffer);
  72175. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72176. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72177. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72178. return cubeMapData;
  72179. };
  72180. /**
  72181. * Returns the pixels data extracted from an RGBE texture.
  72182. * This pixels will be stored left to right up to down in the R G B order in one array.
  72183. *
  72184. * More information on this format are available here:
  72185. * https://en.wikipedia.org/wiki/RGBE_image_format
  72186. *
  72187. * @param uint8array The binary file stored in an array buffer.
  72188. * @param hdrInfo The header information of the file.
  72189. * @return The pixels data in RGB right to left up to down order.
  72190. */
  72191. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72192. // Keep for multi format supports.
  72193. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72194. };
  72195. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72196. var num_scanlines = hdrInfo.height;
  72197. var scanline_width = hdrInfo.width;
  72198. var a, b, c, d, count;
  72199. var dataIndex = hdrInfo.dataPosition;
  72200. var index = 0, endIndex = 0, i = 0;
  72201. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72202. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72203. // 3 channels of 4 bytes per pixel in float.
  72204. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72205. var resultArray = new Float32Array(resultBuffer);
  72206. // read in each successive scanline
  72207. while (num_scanlines > 0) {
  72208. a = uint8array[dataIndex++];
  72209. b = uint8array[dataIndex++];
  72210. c = uint8array[dataIndex++];
  72211. d = uint8array[dataIndex++];
  72212. if (a != 2 || b != 2 || (c & 0x80)) {
  72213. // this file is not run length encoded
  72214. throw "HDR Bad header format, not RLE";
  72215. }
  72216. if (((c << 8) | d) != scanline_width) {
  72217. throw "HDR Bad header format, wrong scan line width";
  72218. }
  72219. index = 0;
  72220. // read each of the four channels for the scanline into the buffer
  72221. for (i = 0; i < 4; i++) {
  72222. endIndex = (i + 1) * scanline_width;
  72223. while (index < endIndex) {
  72224. a = uint8array[dataIndex++];
  72225. b = uint8array[dataIndex++];
  72226. if (a > 128) {
  72227. // a run of the same value
  72228. count = a - 128;
  72229. if ((count == 0) || (count > endIndex - index)) {
  72230. throw "HDR Bad Format, bad scanline data (run)";
  72231. }
  72232. while (count-- > 0) {
  72233. scanLineArray[index++] = b;
  72234. }
  72235. }
  72236. else {
  72237. // a non-run
  72238. count = a;
  72239. if ((count == 0) || (count > endIndex - index)) {
  72240. throw "HDR Bad Format, bad scanline data (non-run)";
  72241. }
  72242. scanLineArray[index++] = b;
  72243. if (--count > 0) {
  72244. for (var j = 0; j < count; j++) {
  72245. scanLineArray[index++] = uint8array[dataIndex++];
  72246. }
  72247. }
  72248. }
  72249. }
  72250. }
  72251. // now convert data from buffer into floats
  72252. for (i = 0; i < scanline_width; i++) {
  72253. a = scanLineArray[i];
  72254. b = scanLineArray[i + scanline_width];
  72255. c = scanLineArray[i + 2 * scanline_width];
  72256. d = scanLineArray[i + 3 * scanline_width];
  72257. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72258. }
  72259. num_scanlines--;
  72260. }
  72261. return resultArray;
  72262. };
  72263. return HDRTools;
  72264. }());
  72265. BABYLON.HDRTools = HDRTools;
  72266. })(BABYLON || (BABYLON = {}));
  72267. //# sourceMappingURL=babylon.hdr.js.map
  72268. var BABYLON;
  72269. (function (BABYLON) {
  72270. /**
  72271. * This represents a texture coming from an HDR input.
  72272. *
  72273. * The only supported format is currently panorama picture stored in RGBE format.
  72274. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72275. */
  72276. var HDRCubeTexture = /** @class */ (function (_super) {
  72277. __extends(HDRCubeTexture, _super);
  72278. /**
  72279. * Instantiates an HDRTexture from the following parameters.
  72280. *
  72281. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72282. * @param scene The scene the texture will be used in
  72283. * @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.
  72284. * @param noMipmap Forces to not generate the mipmap if true
  72285. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72286. * @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)
  72287. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72288. */
  72289. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72290. if (noMipmap === void 0) { noMipmap = false; }
  72291. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72292. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72293. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72294. if (onLoad === void 0) { onLoad = null; }
  72295. if (onError === void 0) { onError = null; }
  72296. var _this = _super.call(this, scene) || this;
  72297. _this._useInGammaSpace = false;
  72298. _this._generateHarmonics = true;
  72299. _this._isBABYLONPreprocessed = false;
  72300. _this._onLoad = null;
  72301. _this._onError = null;
  72302. /**
  72303. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72304. */
  72305. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72306. /**
  72307. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72308. * This is usefull at run time to apply the good shader.
  72309. */
  72310. _this.isPMREM = false;
  72311. _this._isBlocking = true;
  72312. /**
  72313. * Gets or sets the center of the bounding box associated with the cube texture
  72314. * It must define where the camera used to render the texture was set
  72315. */
  72316. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72317. if (!url) {
  72318. return _this;
  72319. }
  72320. _this.name = url;
  72321. _this.url = url;
  72322. _this.hasAlpha = false;
  72323. _this.isCube = true;
  72324. _this._textureMatrix = BABYLON.Matrix.Identity();
  72325. _this._onLoad = onLoad;
  72326. _this._onError = onError;
  72327. _this.gammaSpace = false;
  72328. var caps = scene.getEngine().getCaps();
  72329. if (size) {
  72330. _this._isBABYLONPreprocessed = false;
  72331. _this._noMipmap = noMipmap;
  72332. _this._size = size;
  72333. _this._useInGammaSpace = useInGammaSpace;
  72334. _this._usePMREMGenerator = usePMREMGenerator &&
  72335. caps.textureLOD &&
  72336. caps.textureFloat &&
  72337. !_this._useInGammaSpace;
  72338. }
  72339. else {
  72340. _this._isBABYLONPreprocessed = true;
  72341. _this._noMipmap = false;
  72342. _this._useInGammaSpace = false;
  72343. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72344. !_this._useInGammaSpace;
  72345. }
  72346. _this.isPMREM = _this._usePMREMGenerator;
  72347. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72348. if (!_this._texture) {
  72349. if (!scene.useDelayedTextureLoading) {
  72350. _this.loadTexture();
  72351. }
  72352. else {
  72353. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72354. }
  72355. }
  72356. return _this;
  72357. }
  72358. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72359. /**
  72360. * Gets wether or not the texture is blocking during loading.
  72361. */
  72362. get: function () {
  72363. return this._isBlocking;
  72364. },
  72365. /**
  72366. * Sets wether or not the texture is blocking during loading.
  72367. */
  72368. set: function (value) {
  72369. this._isBlocking = value;
  72370. },
  72371. enumerable: true,
  72372. configurable: true
  72373. });
  72374. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72375. get: function () {
  72376. return this._boundingBoxSize;
  72377. },
  72378. /**
  72379. * Gets or sets the size of the bounding box associated with the cube texture
  72380. * When defined, the cubemap will switch to local mode
  72381. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72382. * @example https://www.babylonjs-playground.com/#RNASML
  72383. */
  72384. set: function (value) {
  72385. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72386. return;
  72387. }
  72388. this._boundingBoxSize = value;
  72389. var scene = this.getScene();
  72390. if (scene) {
  72391. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72392. }
  72393. },
  72394. enumerable: true,
  72395. configurable: true
  72396. });
  72397. /**
  72398. * Occurs when the file is a preprocessed .babylon.hdr file.
  72399. */
  72400. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72401. var _this = this;
  72402. var mipLevels = 0;
  72403. var floatArrayView = null;
  72404. var scene = this.getScene();
  72405. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72406. var mips = new Array();
  72407. if (!floatArrayView) {
  72408. return mips;
  72409. }
  72410. var startIndex = 30;
  72411. for (var level = 0; level < mipLevels; level++) {
  72412. mips.push([]);
  72413. // Fill each pixel of the mip level.
  72414. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72415. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72416. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72417. mips[level].push(faceData);
  72418. startIndex += faceSize;
  72419. }
  72420. }
  72421. return mips;
  72422. } : null;
  72423. var callback = function (buffer) {
  72424. var scene = _this.getScene();
  72425. if (!scene) {
  72426. return null;
  72427. }
  72428. // Create Native Array Views
  72429. var intArrayView = new Int32Array(buffer);
  72430. floatArrayView = new Float32Array(buffer);
  72431. // Fill header.
  72432. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72433. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72434. // Update Texture Information.
  72435. if (!_this._texture) {
  72436. return null;
  72437. }
  72438. _this._texture.updateSize(_this._size, _this._size);
  72439. // Fill polynomial information.
  72440. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72441. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72442. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72443. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72444. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72445. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72446. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72447. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72448. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72449. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72450. _this.sphericalPolynomial = sphericalPolynomial;
  72451. // Fill pixel data.
  72452. mipLevels = intArrayView[29]; // Number of mip levels.
  72453. var startIndex = 30;
  72454. var data = [];
  72455. var faceSize = Math.pow(_this._size, 2) * 3;
  72456. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72457. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72458. startIndex += faceSize;
  72459. }
  72460. var results = [];
  72461. var byteArray = null;
  72462. // Push each faces.
  72463. for (var k = 0; k < 6; k++) {
  72464. var dataFace = null;
  72465. // To be deprecated.
  72466. if (version === 1) {
  72467. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72468. dataFace = data[j];
  72469. }
  72470. // If special cases.
  72471. if (!mipmapGenerator && dataFace) {
  72472. if (!scene.getEngine().getCaps().textureFloat) {
  72473. // 3 channels of 1 bytes per pixel in bytes.
  72474. var byteBuffer = new ArrayBuffer(faceSize);
  72475. byteArray = new Uint8Array(byteBuffer);
  72476. }
  72477. for (var i = 0; i < _this._size * _this._size; i++) {
  72478. // Put in gamma space if requested.
  72479. if (_this._useInGammaSpace) {
  72480. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72481. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72482. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72483. }
  72484. // Convert to int texture for fallback.
  72485. if (byteArray) {
  72486. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72487. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72488. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72489. // May use luminance instead if the result is not accurate.
  72490. var max = Math.max(Math.max(r, g), b);
  72491. if (max > 255) {
  72492. var scale = 255 / max;
  72493. r *= scale;
  72494. g *= scale;
  72495. b *= scale;
  72496. }
  72497. byteArray[(i * 3) + 0] = r;
  72498. byteArray[(i * 3) + 1] = g;
  72499. byteArray[(i * 3) + 2] = b;
  72500. }
  72501. }
  72502. }
  72503. // Fill the array accordingly.
  72504. if (byteArray) {
  72505. results.push(byteArray);
  72506. }
  72507. else {
  72508. results.push(dataFace);
  72509. }
  72510. }
  72511. return results;
  72512. };
  72513. if (scene) {
  72514. 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);
  72515. }
  72516. };
  72517. /**
  72518. * Occurs when the file is raw .hdr file.
  72519. */
  72520. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72521. var _this = this;
  72522. var callback = function (buffer) {
  72523. var scene = _this.getScene();
  72524. if (!scene) {
  72525. return null;
  72526. }
  72527. // Extract the raw linear data.
  72528. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72529. // Generate harmonics if needed.
  72530. if (_this._generateHarmonics) {
  72531. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72532. _this.sphericalPolynomial = sphericalPolynomial;
  72533. }
  72534. var results = [];
  72535. var byteArray = null;
  72536. // Push each faces.
  72537. for (var j = 0; j < 6; j++) {
  72538. // Create uintarray fallback.
  72539. if (!scene.getEngine().getCaps().textureFloat) {
  72540. // 3 channels of 1 bytes per pixel in bytes.
  72541. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72542. byteArray = new Uint8Array(byteBuffer);
  72543. }
  72544. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72545. // If special cases.
  72546. if (_this._useInGammaSpace || byteArray) {
  72547. for (var i = 0; i < _this._size * _this._size; i++) {
  72548. // Put in gamma space if requested.
  72549. if (_this._useInGammaSpace) {
  72550. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72551. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72552. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72553. }
  72554. // Convert to int texture for fallback.
  72555. if (byteArray) {
  72556. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72557. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72558. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72559. // May use luminance instead if the result is not accurate.
  72560. var max = Math.max(Math.max(r, g), b);
  72561. if (max > 255) {
  72562. var scale = 255 / max;
  72563. r *= scale;
  72564. g *= scale;
  72565. b *= scale;
  72566. }
  72567. byteArray[(i * 3) + 0] = r;
  72568. byteArray[(i * 3) + 1] = g;
  72569. byteArray[(i * 3) + 2] = b;
  72570. }
  72571. }
  72572. }
  72573. if (byteArray) {
  72574. results.push(byteArray);
  72575. }
  72576. else {
  72577. results.push(dataFace);
  72578. }
  72579. }
  72580. return results;
  72581. };
  72582. var mipmapGenerator = null;
  72583. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72584. // if (!this._noMipmap &&
  72585. // this._usePMREMGenerator) {
  72586. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72587. // // Custom setup of the generator matching with the PBR shader values.
  72588. // var generator = new BABYLON.PMREMGenerator(data,
  72589. // this._size,
  72590. // this._size,
  72591. // 0,
  72592. // 3,
  72593. // this.getScene().getEngine().getCaps().textureFloat,
  72594. // 2048,
  72595. // 0.25,
  72596. // false,
  72597. // true);
  72598. // return generator.filterCubeMap();
  72599. // };
  72600. // }
  72601. var scene = this.getScene();
  72602. if (scene) {
  72603. 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);
  72604. }
  72605. };
  72606. /**
  72607. * Starts the loading process of the texture.
  72608. */
  72609. HDRCubeTexture.prototype.loadTexture = function () {
  72610. if (this._isBABYLONPreprocessed) {
  72611. this.loadBabylonTexture();
  72612. }
  72613. else {
  72614. this.loadHDRTexture();
  72615. }
  72616. };
  72617. HDRCubeTexture.prototype.clone = function () {
  72618. var scene = this.getScene();
  72619. if (!scene) {
  72620. return this;
  72621. }
  72622. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72623. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72624. // Base texture
  72625. newTexture.level = this.level;
  72626. newTexture.wrapU = this.wrapU;
  72627. newTexture.wrapV = this.wrapV;
  72628. newTexture.coordinatesIndex = this.coordinatesIndex;
  72629. newTexture.coordinatesMode = this.coordinatesMode;
  72630. return newTexture;
  72631. };
  72632. // Methods
  72633. HDRCubeTexture.prototype.delayLoad = function () {
  72634. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72635. return;
  72636. }
  72637. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72638. this._texture = this._getFromCache(this.url, this._noMipmap);
  72639. if (!this._texture) {
  72640. this.loadTexture();
  72641. }
  72642. };
  72643. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72644. return this._textureMatrix;
  72645. };
  72646. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72647. this._textureMatrix = value;
  72648. };
  72649. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72650. var texture = null;
  72651. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72652. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72653. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72654. texture.name = parsedTexture.name;
  72655. texture.hasAlpha = parsedTexture.hasAlpha;
  72656. texture.level = parsedTexture.level;
  72657. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72658. texture.isBlocking = parsedTexture.isBlocking;
  72659. }
  72660. if (texture) {
  72661. if (parsedTexture.boundingBoxPosition) {
  72662. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72663. }
  72664. if (parsedTexture.boundingBoxSize) {
  72665. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72666. }
  72667. }
  72668. return texture;
  72669. };
  72670. HDRCubeTexture.prototype.serialize = function () {
  72671. if (!this.name) {
  72672. return null;
  72673. }
  72674. var serializationObject = {};
  72675. serializationObject.name = this.name;
  72676. serializationObject.hasAlpha = this.hasAlpha;
  72677. serializationObject.isCube = true;
  72678. serializationObject.level = this.level;
  72679. serializationObject.size = this._size;
  72680. serializationObject.coordinatesMode = this.coordinatesMode;
  72681. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72682. serializationObject.generateHarmonics = this._generateHarmonics;
  72683. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72684. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72685. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72686. serializationObject.noMipmap = this._noMipmap;
  72687. serializationObject.isBlocking = this._isBlocking;
  72688. return serializationObject;
  72689. };
  72690. /**
  72691. * Saves as a file the data contained in the texture in a binary format.
  72692. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72693. * as the spherical used in the lighting.
  72694. * @param url The HDR file url.
  72695. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72696. * @param onError Method called if any error happens during download.
  72697. * @return The packed binary data.
  72698. */
  72699. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72700. if (onError === void 0) { onError = null; }
  72701. var callback = function (buffer) {
  72702. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72703. // Returns a URL you can use as a href.
  72704. var objUrl = window.URL.createObjectURL(data);
  72705. // Simulates a link to it and click to dowload.
  72706. var a = document.createElement("a");
  72707. document.body.appendChild(a);
  72708. a.style.display = "none";
  72709. a.href = objUrl;
  72710. a.download = "envmap.babylon.hdr";
  72711. a.click();
  72712. };
  72713. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72714. };
  72715. /**
  72716. * Serializes the data contained in the texture in a binary format.
  72717. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72718. * as the spherical used in the lighting.
  72719. * @param url The HDR file url.
  72720. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72721. * @param onError Method called if any error happens during download.
  72722. * @return The packed binary data.
  72723. */
  72724. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72725. if (onError === void 0) { onError = null; }
  72726. // Needs the url tho create the texture.
  72727. if (!url) {
  72728. return;
  72729. }
  72730. // Check Power of two size.
  72731. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72732. return;
  72733. }
  72734. // Coming Back in 3.x.
  72735. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72736. };
  72737. HDRCubeTexture._facesMapping = [
  72738. "right",
  72739. "left",
  72740. "up",
  72741. "down",
  72742. "front",
  72743. "back"
  72744. ];
  72745. return HDRCubeTexture;
  72746. }(BABYLON.BaseTexture));
  72747. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72748. })(BABYLON || (BABYLON = {}));
  72749. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72750. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72751. // Huge respect for a such great lib.
  72752. // Earcut license:
  72753. // Copyright (c) 2016, Mapbox
  72754. //
  72755. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72756. // with or without fee is hereby granted, provided that the above copyright notice
  72757. // and this permission notice appear in all copies.
  72758. //
  72759. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72760. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72761. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72762. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72763. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72764. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72765. // THIS SOFTWARE.
  72766. var Earcut;
  72767. (function (Earcut) {
  72768. /**
  72769. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72770. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72771. * @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).
  72772. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72773. */
  72774. function earcut(data, holeIndices, dim) {
  72775. dim = dim || 2;
  72776. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72777. if (!outerNode)
  72778. return triangles;
  72779. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72780. if (hasHoles)
  72781. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72782. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72783. if (data.length > 80 * dim) {
  72784. minX = maxX = data[0];
  72785. minY = maxY = data[1];
  72786. for (var i = dim; i < outerLen; i += dim) {
  72787. x = data[i];
  72788. y = data[i + 1];
  72789. if (x < minX)
  72790. minX = x;
  72791. if (y < minY)
  72792. minY = y;
  72793. if (x > maxX)
  72794. maxX = x;
  72795. if (y > maxY)
  72796. maxY = y;
  72797. }
  72798. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72799. size = Math.max(maxX - minX, maxY - minY);
  72800. }
  72801. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72802. return triangles;
  72803. }
  72804. Earcut.earcut = earcut;
  72805. var Node = /** @class */ (function () {
  72806. function Node(i, x, y) {
  72807. this.i = i;
  72808. this.x = x;
  72809. this.y = y;
  72810. this.prev = null;
  72811. this.next = null;
  72812. this.z = null;
  72813. this.prevZ = null;
  72814. this.nextZ = null;
  72815. this.steiner = false;
  72816. }
  72817. return Node;
  72818. }());
  72819. // create a circular doubly linked list from polygon points in the specified winding order
  72820. function linkedList(data, start, end, dim, clockwise) {
  72821. var i, last = null;
  72822. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72823. for (i = start; i < end; i += dim)
  72824. last = insertNode(i, data[i], data[i + 1], last);
  72825. }
  72826. else {
  72827. for (i = end - dim; i >= start; i -= dim)
  72828. last = insertNode(i, data[i], data[i + 1], last);
  72829. }
  72830. if (last && equals(last, last.next)) {
  72831. removeNode(last);
  72832. last = last.next;
  72833. }
  72834. return last;
  72835. }
  72836. // eliminate colinear or duplicate points
  72837. function filterPoints(start, end) {
  72838. if (!start)
  72839. return start;
  72840. if (!end)
  72841. end = start;
  72842. var p = start, again;
  72843. do {
  72844. again = false;
  72845. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72846. removeNode(p);
  72847. p = end = p.prev;
  72848. if (p === p.next)
  72849. return undefined;
  72850. again = true;
  72851. }
  72852. else {
  72853. p = p.next;
  72854. }
  72855. } while (again || p !== end);
  72856. return end;
  72857. }
  72858. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72859. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72860. if (!ear)
  72861. return;
  72862. // interlink polygon nodes in z-order
  72863. if (!pass && size)
  72864. indexCurve(ear, minX, minY, size);
  72865. var stop = ear, prev, next;
  72866. // iterate through ears, slicing them one by one
  72867. while (ear.prev !== ear.next) {
  72868. prev = ear.prev;
  72869. next = ear.next;
  72870. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72871. // cut off the triangle
  72872. triangles.push(prev.i / dim);
  72873. triangles.push(ear.i / dim);
  72874. triangles.push(next.i / dim);
  72875. removeNode(ear);
  72876. // skipping the next vertice leads to less sliver triangles
  72877. ear = next.next;
  72878. stop = next.next;
  72879. continue;
  72880. }
  72881. ear = next;
  72882. // if we looped through the whole remaining polygon and can't find any more ears
  72883. if (ear === stop) {
  72884. // try filtering points and slicing again
  72885. if (!pass) {
  72886. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72887. // if this didn't work, try curing all small self-intersections locally
  72888. }
  72889. else if (pass === 1) {
  72890. ear = cureLocalIntersections(ear, triangles, dim);
  72891. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72892. // as a last resort, try splitting the remaining polygon into two
  72893. }
  72894. else if (pass === 2) {
  72895. splitEarcut(ear, triangles, dim, minX, minY, size);
  72896. }
  72897. break;
  72898. }
  72899. }
  72900. }
  72901. // check whether a polygon node forms a valid ear with adjacent nodes
  72902. function isEar(ear) {
  72903. var a = ear.prev, b = ear, c = ear.next;
  72904. if (area(a, b, c) >= 0)
  72905. return false; // reflex, can't be an ear
  72906. // now make sure we don't have other points inside the potential ear
  72907. var p = ear.next.next;
  72908. while (p !== ear.prev) {
  72909. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72910. area(p.prev, p, p.next) >= 0)
  72911. return false;
  72912. p = p.next;
  72913. }
  72914. return true;
  72915. }
  72916. function isEarHashed(ear, minX, minY, size) {
  72917. var a = ear.prev, b = ear, c = ear.next;
  72918. if (area(a, b, c) >= 0)
  72919. return false; // reflex, can't be an ear
  72920. // triangle bbox; min & max are calculated like this for speed
  72921. 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);
  72922. // z-order range for the current triangle bbox;
  72923. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72924. // first look for points inside the triangle in increasing z-order
  72925. var p = ear.nextZ;
  72926. while (p && p.z <= maxZ) {
  72927. if (p !== ear.prev &&
  72928. p !== ear.next &&
  72929. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72930. area(p.prev, p, p.next) >= 0)
  72931. return false;
  72932. p = p.nextZ;
  72933. }
  72934. // then look for points in decreasing z-order
  72935. p = ear.prevZ;
  72936. while (p && p.z >= minZ) {
  72937. if (p !== ear.prev &&
  72938. p !== ear.next &&
  72939. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72940. area(p.prev, p, p.next) >= 0)
  72941. return false;
  72942. p = p.prevZ;
  72943. }
  72944. return true;
  72945. }
  72946. // go through all polygon nodes and cure small local self-intersections
  72947. function cureLocalIntersections(start, triangles, dim) {
  72948. var p = start;
  72949. do {
  72950. var a = p.prev, b = p.next.next;
  72951. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  72952. triangles.push(a.i / dim);
  72953. triangles.push(p.i / dim);
  72954. triangles.push(b.i / dim);
  72955. // remove two nodes involved
  72956. removeNode(p);
  72957. removeNode(p.next);
  72958. p = start = b;
  72959. }
  72960. p = p.next;
  72961. } while (p !== start);
  72962. return p;
  72963. }
  72964. // try splitting polygon into two and triangulate them independently
  72965. function splitEarcut(start, triangles, dim, minX, minY, size) {
  72966. // look for a valid diagonal that divides the polygon into two
  72967. var a = start;
  72968. do {
  72969. var b = a.next.next;
  72970. while (b !== a.prev) {
  72971. if (a.i !== b.i && isValidDiagonal(a, b)) {
  72972. // split the polygon in two by the diagonal
  72973. var c = splitPolygon(a, b);
  72974. // filter colinear points around the cuts
  72975. a = filterPoints(a, a.next);
  72976. c = filterPoints(c, c.next);
  72977. // run earcut on each half
  72978. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  72979. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  72980. return;
  72981. }
  72982. b = b.next;
  72983. }
  72984. a = a.next;
  72985. } while (a !== start);
  72986. }
  72987. // link every hole into the outer loop, producing a single-ring polygon without holes
  72988. function eliminateHoles(data, holeIndices, outerNode, dim) {
  72989. var queue = [], i, len, start, end, list;
  72990. for (i = 0, len = holeIndices.length; i < len; i++) {
  72991. start = holeIndices[i] * dim;
  72992. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72993. list = linkedList(data, start, end, dim, false);
  72994. if (list === list.next)
  72995. list.steiner = true;
  72996. queue.push(getLeftmost(list));
  72997. }
  72998. queue.sort(compareX);
  72999. // process holes from left to right
  73000. for (i = 0; i < queue.length; i++) {
  73001. eliminateHole(queue[i], outerNode);
  73002. outerNode = filterPoints(outerNode, outerNode.next);
  73003. }
  73004. return outerNode;
  73005. }
  73006. function compareX(a, b) {
  73007. return a.x - b.x;
  73008. }
  73009. // find a bridge between vertices that connects hole with an outer ring and and link it
  73010. function eliminateHole(hole, outerNode) {
  73011. outerNode = findHoleBridge(hole, outerNode);
  73012. if (outerNode) {
  73013. var b = splitPolygon(outerNode, hole);
  73014. filterPoints(b, b.next);
  73015. }
  73016. }
  73017. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73018. function findHoleBridge(hole, outerNode) {
  73019. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73020. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73021. // segment's endpoint with lesser x will be potential connection point
  73022. do {
  73023. if (hy <= p.y && hy >= p.next.y) {
  73024. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73025. if (x <= hx && x > qx) {
  73026. qx = x;
  73027. if (x === hx) {
  73028. if (hy === p.y)
  73029. return p;
  73030. if (hy === p.next.y)
  73031. return p.next;
  73032. }
  73033. m = p.x < p.next.x ? p : p.next;
  73034. }
  73035. }
  73036. p = p.next;
  73037. } while (p !== outerNode);
  73038. if (!m)
  73039. return null;
  73040. if (hx === qx)
  73041. return m.prev; // hole touches outer segment; pick lower endpoint
  73042. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73043. // if there are no points found, we have a valid connection;
  73044. // otherwise choose the point of the minimum angle with the ray as connection point
  73045. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73046. p = m.next;
  73047. while (p !== stop) {
  73048. if (hx >= p.x &&
  73049. p.x >= mx &&
  73050. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73051. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73052. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73053. m = p;
  73054. tanMin = tan;
  73055. }
  73056. }
  73057. p = p.next;
  73058. }
  73059. return m;
  73060. }
  73061. // interlink polygon nodes in z-order
  73062. function indexCurve(start, minX, minY, size) {
  73063. var p = start;
  73064. do {
  73065. if (p.z === null)
  73066. p.z = zOrder(p.x, p.y, minX, minY, size);
  73067. p.prevZ = p.prev;
  73068. p.nextZ = p.next;
  73069. p = p.next;
  73070. } while (p !== start);
  73071. p.prevZ.nextZ = null;
  73072. p.prevZ = null;
  73073. sortLinked(p);
  73074. }
  73075. // Simon Tatham's linked list merge sort algorithm
  73076. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73077. function sortLinked(list) {
  73078. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73079. do {
  73080. p = list;
  73081. list = null;
  73082. tail = null;
  73083. numMerges = 0;
  73084. while (p) {
  73085. numMerges++;
  73086. q = p;
  73087. pSize = 0;
  73088. for (i = 0; i < inSize; i++) {
  73089. pSize++;
  73090. q = q.nextZ;
  73091. if (!q)
  73092. break;
  73093. }
  73094. qSize = inSize;
  73095. while (pSize > 0 || (qSize > 0 && q)) {
  73096. if (pSize === 0) {
  73097. e = q;
  73098. q = q.nextZ;
  73099. qSize--;
  73100. }
  73101. else if (qSize === 0 || !q) {
  73102. e = p;
  73103. p = p.nextZ;
  73104. pSize--;
  73105. }
  73106. else if (p.z <= q.z) {
  73107. e = p;
  73108. p = p.nextZ;
  73109. pSize--;
  73110. }
  73111. else {
  73112. e = q;
  73113. q = q.nextZ;
  73114. qSize--;
  73115. }
  73116. if (tail)
  73117. tail.nextZ = e;
  73118. else
  73119. list = e;
  73120. e.prevZ = tail;
  73121. tail = e;
  73122. }
  73123. p = q;
  73124. }
  73125. tail.nextZ = null;
  73126. inSize *= 2;
  73127. } while (numMerges > 1);
  73128. return list;
  73129. }
  73130. // z-order of a point given coords and size of the data bounding box
  73131. function zOrder(x, y, minX, minY, size) {
  73132. // coords are transformed into non-negative 15-bit integer range
  73133. x = 32767 * (x - minX) / size;
  73134. y = 32767 * (y - minY) / size;
  73135. x = (x | (x << 8)) & 0x00FF00FF;
  73136. x = (x | (x << 4)) & 0x0F0F0F0F;
  73137. x = (x | (x << 2)) & 0x33333333;
  73138. x = (x | (x << 1)) & 0x55555555;
  73139. y = (y | (y << 8)) & 0x00FF00FF;
  73140. y = (y | (y << 4)) & 0x0F0F0F0F;
  73141. y = (y | (y << 2)) & 0x33333333;
  73142. y = (y | (y << 1)) & 0x55555555;
  73143. return x | (y << 1);
  73144. }
  73145. // find the leftmost node of a polygon ring
  73146. function getLeftmost(start) {
  73147. var p = start, leftmost = start;
  73148. do {
  73149. if (p.x < leftmost.x)
  73150. leftmost = p;
  73151. p = p.next;
  73152. } while (p !== start);
  73153. return leftmost;
  73154. }
  73155. // check if a point lies within a convex triangle
  73156. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73157. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73158. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73159. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73160. }
  73161. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73162. function isValidDiagonal(a, b) {
  73163. return a.next.i !== b.i &&
  73164. a.prev.i !== b.i &&
  73165. !intersectsPolygon(a, b) &&
  73166. locallyInside(a, b) &&
  73167. locallyInside(b, a) &&
  73168. middleInside(a, b);
  73169. }
  73170. // signed area of a triangle
  73171. function area(p, q, r) {
  73172. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73173. }
  73174. // check if two points are equal
  73175. function equals(p1, p2) {
  73176. return p1.x === p2.x && p1.y === p2.y;
  73177. }
  73178. // check if two segments intersect
  73179. function intersects(p1, q1, p2, q2) {
  73180. if ((equals(p1, q1) && equals(p2, q2)) ||
  73181. (equals(p1, q2) && equals(p2, q1)))
  73182. return true;
  73183. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73184. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73185. }
  73186. // check if a polygon diagonal intersects any polygon segments
  73187. function intersectsPolygon(a, b) {
  73188. var p = a;
  73189. do {
  73190. if (p.i !== a.i &&
  73191. p.next.i !== a.i &&
  73192. p.i !== b.i &&
  73193. p.next.i !== b.i &&
  73194. intersects(p, p.next, a, b))
  73195. return true;
  73196. p = p.next;
  73197. } while (p !== a);
  73198. return false;
  73199. }
  73200. // check if a polygon diagonal is locally inside the polygon
  73201. function locallyInside(a, b) {
  73202. return area(a.prev, a, a.next) < 0
  73203. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73204. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73205. }
  73206. // check if the middle point of a polygon diagonal is inside the polygon
  73207. function middleInside(a, b) {
  73208. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73209. do {
  73210. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73211. inside = !inside;
  73212. p = p.next;
  73213. } while (p !== a);
  73214. return inside;
  73215. }
  73216. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73217. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73218. function splitPolygon(a, b) {
  73219. 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;
  73220. a.next = b;
  73221. b.prev = a;
  73222. a2.next = an;
  73223. an.prev = a2;
  73224. b2.next = a2;
  73225. a2.prev = b2;
  73226. bp.next = b2;
  73227. b2.prev = bp;
  73228. return b2;
  73229. }
  73230. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73231. function insertNode(i, x, y, last) {
  73232. var p = new Node(i, x, y);
  73233. if (!last) {
  73234. p.prev = p;
  73235. p.next = p;
  73236. }
  73237. else {
  73238. p.next = last.next;
  73239. p.prev = last;
  73240. last.next.prev = p;
  73241. last.next = p;
  73242. }
  73243. return p;
  73244. }
  73245. function removeNode(p) {
  73246. p.next.prev = p.prev;
  73247. p.prev.next = p.next;
  73248. if (p.prevZ)
  73249. p.prevZ.nextZ = p.nextZ;
  73250. if (p.nextZ)
  73251. p.nextZ.prevZ = p.prevZ;
  73252. }
  73253. /**
  73254. * return a percentage difference between the polygon area and its triangulation area;
  73255. * used to verify correctness of triangulation
  73256. */
  73257. function deviation(data, holeIndices, dim, triangles) {
  73258. var hasHoles = holeIndices && holeIndices.length;
  73259. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73260. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73261. if (hasHoles) {
  73262. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73263. var start = holeIndices[i] * dim;
  73264. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73265. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73266. }
  73267. }
  73268. var trianglesArea = 0;
  73269. for (i = 0; i < triangles.length; i += 3) {
  73270. var a = triangles[i] * dim;
  73271. var b = triangles[i + 1] * dim;
  73272. var c = triangles[i + 2] * dim;
  73273. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73274. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73275. }
  73276. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73277. }
  73278. Earcut.deviation = deviation;
  73279. ;
  73280. function signedArea(data, start, end, dim) {
  73281. var sum = 0;
  73282. for (var i = start, j = end - dim; i < end; i += dim) {
  73283. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73284. j = i;
  73285. }
  73286. return sum;
  73287. }
  73288. /**
  73289. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73290. */
  73291. function flatten(data) {
  73292. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73293. for (var i = 0; i < data.length; i++) {
  73294. for (var j = 0; j < data[i].length; j++) {
  73295. for (var d = 0; d < dim; d++)
  73296. result.vertices.push(data[i][j][d]);
  73297. }
  73298. if (i > 0) {
  73299. holeIndex += data[i - 1].length;
  73300. result.holes.push(holeIndex);
  73301. }
  73302. }
  73303. return result;
  73304. }
  73305. Earcut.flatten = flatten;
  73306. ;
  73307. })(Earcut || (Earcut = {}));
  73308. //# sourceMappingURL=babylon.earcut.js.map
  73309. var BABYLON;
  73310. (function (BABYLON) {
  73311. var IndexedVector2 = /** @class */ (function (_super) {
  73312. __extends(IndexedVector2, _super);
  73313. function IndexedVector2(original, index) {
  73314. var _this = _super.call(this, original.x, original.y) || this;
  73315. _this.index = index;
  73316. return _this;
  73317. }
  73318. return IndexedVector2;
  73319. }(BABYLON.Vector2));
  73320. var PolygonPoints = /** @class */ (function () {
  73321. function PolygonPoints() {
  73322. this.elements = new Array();
  73323. }
  73324. PolygonPoints.prototype.add = function (originalPoints) {
  73325. var _this = this;
  73326. var result = new Array();
  73327. originalPoints.forEach(function (point) {
  73328. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73329. var newPoint = new IndexedVector2(point, _this.elements.length);
  73330. result.push(newPoint);
  73331. _this.elements.push(newPoint);
  73332. }
  73333. });
  73334. return result;
  73335. };
  73336. PolygonPoints.prototype.computeBounds = function () {
  73337. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73338. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73339. this.elements.forEach(function (point) {
  73340. // x
  73341. if (point.x < lmin.x) {
  73342. lmin.x = point.x;
  73343. }
  73344. else if (point.x > lmax.x) {
  73345. lmax.x = point.x;
  73346. }
  73347. // y
  73348. if (point.y < lmin.y) {
  73349. lmin.y = point.y;
  73350. }
  73351. else if (point.y > lmax.y) {
  73352. lmax.y = point.y;
  73353. }
  73354. });
  73355. return {
  73356. min: lmin,
  73357. max: lmax,
  73358. width: lmax.x - lmin.x,
  73359. height: lmax.y - lmin.y
  73360. };
  73361. };
  73362. return PolygonPoints;
  73363. }());
  73364. var Polygon = /** @class */ (function () {
  73365. function Polygon() {
  73366. }
  73367. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73368. return [
  73369. new BABYLON.Vector2(xmin, ymin),
  73370. new BABYLON.Vector2(xmax, ymin),
  73371. new BABYLON.Vector2(xmax, ymax),
  73372. new BABYLON.Vector2(xmin, ymax)
  73373. ];
  73374. };
  73375. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73376. if (cx === void 0) { cx = 0; }
  73377. if (cy === void 0) { cy = 0; }
  73378. if (numberOfSides === void 0) { numberOfSides = 32; }
  73379. var result = new Array();
  73380. var angle = 0;
  73381. var increment = (Math.PI * 2) / numberOfSides;
  73382. for (var i = 0; i < numberOfSides; i++) {
  73383. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73384. angle -= increment;
  73385. }
  73386. return result;
  73387. };
  73388. Polygon.Parse = function (input) {
  73389. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73390. var i, result = [];
  73391. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73392. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73393. }
  73394. return result;
  73395. };
  73396. Polygon.StartingAt = function (x, y) {
  73397. return BABYLON.Path2.StartingAt(x, y);
  73398. };
  73399. return Polygon;
  73400. }());
  73401. BABYLON.Polygon = Polygon;
  73402. var PolygonMeshBuilder = /** @class */ (function () {
  73403. function PolygonMeshBuilder(name, contours, scene) {
  73404. this._points = new PolygonPoints();
  73405. this._outlinepoints = new PolygonPoints();
  73406. this._holes = new Array();
  73407. this._epoints = new Array();
  73408. this._eholes = new Array();
  73409. this._name = name;
  73410. this._scene = scene;
  73411. var points;
  73412. if (contours instanceof BABYLON.Path2) {
  73413. points = contours.getPoints();
  73414. }
  73415. else {
  73416. points = contours;
  73417. }
  73418. this._addToepoint(points);
  73419. this._points.add(points);
  73420. this._outlinepoints.add(points);
  73421. }
  73422. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73423. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73424. var p = points_1[_i];
  73425. this._epoints.push(p.x, p.y);
  73426. }
  73427. };
  73428. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73429. this._points.add(hole);
  73430. var holepoints = new PolygonPoints();
  73431. holepoints.add(hole);
  73432. this._holes.push(holepoints);
  73433. this._eholes.push(this._epoints.length / 2);
  73434. this._addToepoint(hole);
  73435. return this;
  73436. };
  73437. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73438. var _this = this;
  73439. if (updatable === void 0) { updatable = false; }
  73440. if (depth === void 0) { depth = 0; }
  73441. var result = new BABYLON.Mesh(this._name, this._scene);
  73442. var normals = new Array();
  73443. var positions = new Array();
  73444. var uvs = new Array();
  73445. var bounds = this._points.computeBounds();
  73446. this._points.elements.forEach(function (p) {
  73447. normals.push(0, 1.0, 0);
  73448. positions.push(p.x, 0, p.y);
  73449. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73450. });
  73451. var indices = new Array();
  73452. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73453. for (var i = 0; i < res.length; i++) {
  73454. indices.push(res[i]);
  73455. }
  73456. if (depth > 0) {
  73457. var positionscount = (positions.length / 3); //get the current pointcount
  73458. this._points.elements.forEach(function (p) {
  73459. normals.push(0, -1.0, 0);
  73460. positions.push(p.x, -depth, p.y);
  73461. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73462. });
  73463. var totalCount = indices.length;
  73464. for (var i = 0; i < totalCount; i += 3) {
  73465. var i0 = indices[i + 0];
  73466. var i1 = indices[i + 1];
  73467. var i2 = indices[i + 2];
  73468. indices.push(i2 + positionscount);
  73469. indices.push(i1 + positionscount);
  73470. indices.push(i0 + positionscount);
  73471. }
  73472. //Add the sides
  73473. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73474. this._holes.forEach(function (hole) {
  73475. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73476. });
  73477. }
  73478. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73479. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73480. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73481. result.setIndices(indices);
  73482. return result;
  73483. };
  73484. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73485. var StartIndex = positions.length / 3;
  73486. var ulength = 0;
  73487. for (var i = 0; i < points.elements.length; i++) {
  73488. var p = points.elements[i];
  73489. var p1;
  73490. if ((i + 1) > points.elements.length - 1) {
  73491. p1 = points.elements[0];
  73492. }
  73493. else {
  73494. p1 = points.elements[i + 1];
  73495. }
  73496. positions.push(p.x, 0, p.y);
  73497. positions.push(p.x, -depth, p.y);
  73498. positions.push(p1.x, 0, p1.y);
  73499. positions.push(p1.x, -depth, p1.y);
  73500. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73501. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73502. var v3 = v2.subtract(v1);
  73503. var v4 = new BABYLON.Vector3(0, 1, 0);
  73504. var vn = BABYLON.Vector3.Cross(v3, v4);
  73505. vn = vn.normalize();
  73506. uvs.push(ulength / bounds.width, 0);
  73507. uvs.push(ulength / bounds.width, 1);
  73508. ulength += v3.length();
  73509. uvs.push((ulength / bounds.width), 0);
  73510. uvs.push((ulength / bounds.width), 1);
  73511. if (!flip) {
  73512. normals.push(-vn.x, -vn.y, -vn.z);
  73513. normals.push(-vn.x, -vn.y, -vn.z);
  73514. normals.push(-vn.x, -vn.y, -vn.z);
  73515. normals.push(-vn.x, -vn.y, -vn.z);
  73516. indices.push(StartIndex);
  73517. indices.push(StartIndex + 1);
  73518. indices.push(StartIndex + 2);
  73519. indices.push(StartIndex + 1);
  73520. indices.push(StartIndex + 3);
  73521. indices.push(StartIndex + 2);
  73522. }
  73523. else {
  73524. normals.push(vn.x, vn.y, vn.z);
  73525. normals.push(vn.x, vn.y, vn.z);
  73526. normals.push(vn.x, vn.y, vn.z);
  73527. normals.push(vn.x, vn.y, vn.z);
  73528. indices.push(StartIndex);
  73529. indices.push(StartIndex + 2);
  73530. indices.push(StartIndex + 1);
  73531. indices.push(StartIndex + 1);
  73532. indices.push(StartIndex + 2);
  73533. indices.push(StartIndex + 3);
  73534. }
  73535. StartIndex += 4;
  73536. }
  73537. ;
  73538. };
  73539. return PolygonMeshBuilder;
  73540. }());
  73541. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73542. })(BABYLON || (BABYLON = {}));
  73543. //# sourceMappingURL=babylon.polygonMesh.js.map
  73544. var BABYLON;
  73545. (function (BABYLON) {
  73546. // Unique ID when we import meshes from Babylon to CSG
  73547. var currentCSGMeshId = 0;
  73548. // # class Vertex
  73549. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73550. // one to provide additional features like texture coordinates and vertex
  73551. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73552. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73553. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73554. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73555. // is not used anywhere else.
  73556. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73557. var Vertex = /** @class */ (function () {
  73558. function Vertex(pos, normal, uv) {
  73559. this.pos = pos;
  73560. this.normal = normal;
  73561. this.uv = uv;
  73562. }
  73563. Vertex.prototype.clone = function () {
  73564. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73565. };
  73566. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73567. // orientation of a polygon is flipped.
  73568. Vertex.prototype.flip = function () {
  73569. this.normal = this.normal.scale(-1);
  73570. };
  73571. // Create a new vertex between this vertex and `other` by linearly
  73572. // interpolating all properties using a parameter of `t`. Subclasses should
  73573. // override this to interpolate additional properties.
  73574. Vertex.prototype.interpolate = function (other, t) {
  73575. 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));
  73576. };
  73577. return Vertex;
  73578. }());
  73579. // # class Plane
  73580. // Represents a plane in 3D space.
  73581. var Plane = /** @class */ (function () {
  73582. function Plane(normal, w) {
  73583. this.normal = normal;
  73584. this.w = w;
  73585. }
  73586. Plane.FromPoints = function (a, b, c) {
  73587. var v0 = c.subtract(a);
  73588. var v1 = b.subtract(a);
  73589. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73590. return null;
  73591. }
  73592. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73593. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73594. };
  73595. Plane.prototype.clone = function () {
  73596. return new Plane(this.normal.clone(), this.w);
  73597. };
  73598. Plane.prototype.flip = function () {
  73599. this.normal.scaleInPlace(-1);
  73600. this.w = -this.w;
  73601. };
  73602. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73603. // fragments in the appropriate lists. Coplanar polygons go into either
  73604. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73605. // respect to this plane. Polygons in front or in back of this plane go into
  73606. // either `front` or `back`.
  73607. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73608. var COPLANAR = 0;
  73609. var FRONT = 1;
  73610. var BACK = 2;
  73611. var SPANNING = 3;
  73612. // Classify each point as well as the entire polygon into one of the above
  73613. // four classes.
  73614. var polygonType = 0;
  73615. var types = [];
  73616. var i;
  73617. var t;
  73618. for (i = 0; i < polygon.vertices.length; i++) {
  73619. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73620. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73621. polygonType |= type;
  73622. types.push(type);
  73623. }
  73624. // Put the polygon in the correct list, splitting it when necessary.
  73625. switch (polygonType) {
  73626. case COPLANAR:
  73627. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73628. break;
  73629. case FRONT:
  73630. front.push(polygon);
  73631. break;
  73632. case BACK:
  73633. back.push(polygon);
  73634. break;
  73635. case SPANNING:
  73636. var f = [], b = [];
  73637. for (i = 0; i < polygon.vertices.length; i++) {
  73638. var j = (i + 1) % polygon.vertices.length;
  73639. var ti = types[i], tj = types[j];
  73640. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73641. if (ti !== BACK)
  73642. f.push(vi);
  73643. if (ti !== FRONT)
  73644. b.push(ti !== BACK ? vi.clone() : vi);
  73645. if ((ti | tj) === SPANNING) {
  73646. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73647. var v = vi.interpolate(vj, t);
  73648. f.push(v);
  73649. b.push(v.clone());
  73650. }
  73651. }
  73652. var poly;
  73653. if (f.length >= 3) {
  73654. poly = new Polygon(f, polygon.shared);
  73655. if (poly.plane)
  73656. front.push(poly);
  73657. }
  73658. if (b.length >= 3) {
  73659. poly = new Polygon(b, polygon.shared);
  73660. if (poly.plane)
  73661. back.push(poly);
  73662. }
  73663. break;
  73664. }
  73665. };
  73666. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73667. // point is on the plane.
  73668. Plane.EPSILON = 1e-5;
  73669. return Plane;
  73670. }());
  73671. // # class Polygon
  73672. // Represents a convex polygon. The vertices used to initialize a polygon must
  73673. // be coplanar and form a convex loop.
  73674. //
  73675. // Each convex polygon has a `shared` property, which is shared between all
  73676. // polygons that are clones of each other or were split from the same polygon.
  73677. // This can be used to define per-polygon properties (such as surface color).
  73678. var Polygon = /** @class */ (function () {
  73679. function Polygon(vertices, shared) {
  73680. this.vertices = vertices;
  73681. this.shared = shared;
  73682. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73683. }
  73684. Polygon.prototype.clone = function () {
  73685. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73686. return new Polygon(vertices, this.shared);
  73687. };
  73688. Polygon.prototype.flip = function () {
  73689. this.vertices.reverse().map(function (v) { v.flip(); });
  73690. this.plane.flip();
  73691. };
  73692. return Polygon;
  73693. }());
  73694. // # class Node
  73695. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73696. // by picking a polygon to split along. That polygon (and all other coplanar
  73697. // polygons) are added directly to that node and the other polygons are added to
  73698. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73699. // no distinction between internal and leaf nodes.
  73700. var Node = /** @class */ (function () {
  73701. function Node(polygons) {
  73702. this.plane = null;
  73703. this.front = null;
  73704. this.back = null;
  73705. this.polygons = new Array();
  73706. if (polygons) {
  73707. this.build(polygons);
  73708. }
  73709. }
  73710. Node.prototype.clone = function () {
  73711. var node = new Node();
  73712. node.plane = this.plane && this.plane.clone();
  73713. node.front = this.front && this.front.clone();
  73714. node.back = this.back && this.back.clone();
  73715. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73716. return node;
  73717. };
  73718. // Convert solid space to empty space and empty space to solid space.
  73719. Node.prototype.invert = function () {
  73720. for (var i = 0; i < this.polygons.length; i++) {
  73721. this.polygons[i].flip();
  73722. }
  73723. if (this.plane) {
  73724. this.plane.flip();
  73725. }
  73726. if (this.front) {
  73727. this.front.invert();
  73728. }
  73729. if (this.back) {
  73730. this.back.invert();
  73731. }
  73732. var temp = this.front;
  73733. this.front = this.back;
  73734. this.back = temp;
  73735. };
  73736. // Recursively remove all polygons in `polygons` that are inside this BSP
  73737. // tree.
  73738. Node.prototype.clipPolygons = function (polygons) {
  73739. if (!this.plane)
  73740. return polygons.slice();
  73741. var front = new Array(), back = new Array();
  73742. for (var i = 0; i < polygons.length; i++) {
  73743. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73744. }
  73745. if (this.front) {
  73746. front = this.front.clipPolygons(front);
  73747. }
  73748. if (this.back) {
  73749. back = this.back.clipPolygons(back);
  73750. }
  73751. else {
  73752. back = [];
  73753. }
  73754. return front.concat(back);
  73755. };
  73756. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73757. // `bsp`.
  73758. Node.prototype.clipTo = function (bsp) {
  73759. this.polygons = bsp.clipPolygons(this.polygons);
  73760. if (this.front)
  73761. this.front.clipTo(bsp);
  73762. if (this.back)
  73763. this.back.clipTo(bsp);
  73764. };
  73765. // Return a list of all polygons in this BSP tree.
  73766. Node.prototype.allPolygons = function () {
  73767. var polygons = this.polygons.slice();
  73768. if (this.front)
  73769. polygons = polygons.concat(this.front.allPolygons());
  73770. if (this.back)
  73771. polygons = polygons.concat(this.back.allPolygons());
  73772. return polygons;
  73773. };
  73774. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73775. // new polygons are filtered down to the bottom of the tree and become new
  73776. // nodes there. Each set of polygons is partitioned using the first polygon
  73777. // (no heuristic is used to pick a good split).
  73778. Node.prototype.build = function (polygons) {
  73779. if (!polygons.length)
  73780. return;
  73781. if (!this.plane)
  73782. this.plane = polygons[0].plane.clone();
  73783. var front = new Array(), back = new Array();
  73784. for (var i = 0; i < polygons.length; i++) {
  73785. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73786. }
  73787. if (front.length) {
  73788. if (!this.front)
  73789. this.front = new Node();
  73790. this.front.build(front);
  73791. }
  73792. if (back.length) {
  73793. if (!this.back)
  73794. this.back = new Node();
  73795. this.back.build(back);
  73796. }
  73797. };
  73798. return Node;
  73799. }());
  73800. var CSG = /** @class */ (function () {
  73801. function CSG() {
  73802. this.polygons = new Array();
  73803. }
  73804. // Convert BABYLON.Mesh to BABYLON.CSG
  73805. CSG.FromMesh = function (mesh) {
  73806. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73807. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73808. if (mesh instanceof BABYLON.Mesh) {
  73809. mesh.computeWorldMatrix(true);
  73810. matrix = mesh.getWorldMatrix();
  73811. meshPosition = mesh.position.clone();
  73812. meshRotation = mesh.rotation.clone();
  73813. if (mesh.rotationQuaternion) {
  73814. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73815. }
  73816. meshScaling = mesh.scaling.clone();
  73817. }
  73818. else {
  73819. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73820. }
  73821. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73822. var subMeshes = mesh.subMeshes;
  73823. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73824. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73825. vertices = [];
  73826. for (var j = 0; j < 3; j++) {
  73827. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73828. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73829. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73830. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73831. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73832. vertex = new Vertex(position, normal, uv);
  73833. vertices.push(vertex);
  73834. }
  73835. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73836. // To handle the case of degenerated triangle
  73837. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73838. if (polygon.plane)
  73839. polygons.push(polygon);
  73840. }
  73841. }
  73842. var csg = CSG.FromPolygons(polygons);
  73843. csg.matrix = matrix;
  73844. csg.position = meshPosition;
  73845. csg.rotation = meshRotation;
  73846. csg.scaling = meshScaling;
  73847. csg.rotationQuaternion = meshRotationQuaternion;
  73848. currentCSGMeshId++;
  73849. return csg;
  73850. };
  73851. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73852. CSG.FromPolygons = function (polygons) {
  73853. var csg = new CSG();
  73854. csg.polygons = polygons;
  73855. return csg;
  73856. };
  73857. CSG.prototype.clone = function () {
  73858. var csg = new CSG();
  73859. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73860. csg.copyTransformAttributes(this);
  73861. return csg;
  73862. };
  73863. CSG.prototype.union = function (csg) {
  73864. var a = new Node(this.clone().polygons);
  73865. var b = new Node(csg.clone().polygons);
  73866. a.clipTo(b);
  73867. b.clipTo(a);
  73868. b.invert();
  73869. b.clipTo(a);
  73870. b.invert();
  73871. a.build(b.allPolygons());
  73872. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73873. };
  73874. CSG.prototype.unionInPlace = function (csg) {
  73875. var a = new Node(this.polygons);
  73876. var b = new Node(csg.polygons);
  73877. a.clipTo(b);
  73878. b.clipTo(a);
  73879. b.invert();
  73880. b.clipTo(a);
  73881. b.invert();
  73882. a.build(b.allPolygons());
  73883. this.polygons = a.allPolygons();
  73884. };
  73885. CSG.prototype.subtract = function (csg) {
  73886. var a = new Node(this.clone().polygons);
  73887. var b = new Node(csg.clone().polygons);
  73888. a.invert();
  73889. a.clipTo(b);
  73890. b.clipTo(a);
  73891. b.invert();
  73892. b.clipTo(a);
  73893. b.invert();
  73894. a.build(b.allPolygons());
  73895. a.invert();
  73896. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73897. };
  73898. CSG.prototype.subtractInPlace = function (csg) {
  73899. var a = new Node(this.polygons);
  73900. var b = new Node(csg.polygons);
  73901. a.invert();
  73902. a.clipTo(b);
  73903. b.clipTo(a);
  73904. b.invert();
  73905. b.clipTo(a);
  73906. b.invert();
  73907. a.build(b.allPolygons());
  73908. a.invert();
  73909. this.polygons = a.allPolygons();
  73910. };
  73911. CSG.prototype.intersect = function (csg) {
  73912. var a = new Node(this.clone().polygons);
  73913. var b = new Node(csg.clone().polygons);
  73914. a.invert();
  73915. b.clipTo(a);
  73916. b.invert();
  73917. a.clipTo(b);
  73918. b.clipTo(a);
  73919. a.build(b.allPolygons());
  73920. a.invert();
  73921. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73922. };
  73923. CSG.prototype.intersectInPlace = function (csg) {
  73924. var a = new Node(this.polygons);
  73925. var b = new Node(csg.polygons);
  73926. a.invert();
  73927. b.clipTo(a);
  73928. b.invert();
  73929. a.clipTo(b);
  73930. b.clipTo(a);
  73931. a.build(b.allPolygons());
  73932. a.invert();
  73933. this.polygons = a.allPolygons();
  73934. };
  73935. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73936. // not modified.
  73937. CSG.prototype.inverse = function () {
  73938. var csg = this.clone();
  73939. csg.inverseInPlace();
  73940. return csg;
  73941. };
  73942. CSG.prototype.inverseInPlace = function () {
  73943. this.polygons.map(function (p) { p.flip(); });
  73944. };
  73945. // This is used to keep meshes transformations so they can be restored
  73946. // when we build back a Babylon Mesh
  73947. // NB : All CSG operations are performed in world coordinates
  73948. CSG.prototype.copyTransformAttributes = function (csg) {
  73949. this.matrix = csg.matrix;
  73950. this.position = csg.position;
  73951. this.rotation = csg.rotation;
  73952. this.scaling = csg.scaling;
  73953. this.rotationQuaternion = csg.rotationQuaternion;
  73954. return this;
  73955. };
  73956. // Build Raw mesh from CSG
  73957. // Coordinates here are in world space
  73958. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  73959. var matrix = this.matrix.clone();
  73960. matrix.invert();
  73961. 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;
  73962. if (keepSubMeshes) {
  73963. // Sort Polygons, since subMeshes are indices range
  73964. polygons.sort(function (a, b) {
  73965. if (a.shared.meshId === b.shared.meshId) {
  73966. return a.shared.subMeshId - b.shared.subMeshId;
  73967. }
  73968. else {
  73969. return a.shared.meshId - b.shared.meshId;
  73970. }
  73971. });
  73972. }
  73973. for (var i = 0, il = polygons.length; i < il; i++) {
  73974. polygon = polygons[i];
  73975. // Building SubMeshes
  73976. if (!subMesh_dict[polygon.shared.meshId]) {
  73977. subMesh_dict[polygon.shared.meshId] = {};
  73978. }
  73979. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  73980. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  73981. indexStart: +Infinity,
  73982. indexEnd: -Infinity,
  73983. materialIndex: polygon.shared.materialIndex
  73984. };
  73985. }
  73986. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  73987. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  73988. polygonIndices[0] = 0;
  73989. polygonIndices[1] = j - 1;
  73990. polygonIndices[2] = j;
  73991. for (var k = 0; k < 3; k++) {
  73992. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  73993. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  73994. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  73995. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  73996. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  73997. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  73998. // Check if 2 points can be merged
  73999. if (!(typeof vertex_idx !== 'undefined' &&
  74000. normals[vertex_idx * 3] === localNormal.x &&
  74001. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74002. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74003. uvs[vertex_idx * 2] === uv.x &&
  74004. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74005. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74006. uvs.push(uv.x, uv.y);
  74007. normals.push(normal.x, normal.y, normal.z);
  74008. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74009. }
  74010. indices.push(vertex_idx);
  74011. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74012. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74013. currentIndex++;
  74014. }
  74015. }
  74016. }
  74017. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74018. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74019. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74020. mesh.setIndices(indices, null);
  74021. if (keepSubMeshes) {
  74022. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74023. var materialIndexOffset = 0, materialMaxIndex;
  74024. mesh.subMeshes = new Array();
  74025. for (var m in subMesh_dict) {
  74026. materialMaxIndex = -1;
  74027. for (var sm in subMesh_dict[m]) {
  74028. subMesh_obj = subMesh_dict[m][sm];
  74029. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74030. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74031. }
  74032. materialIndexOffset += ++materialMaxIndex;
  74033. }
  74034. }
  74035. return mesh;
  74036. };
  74037. // Build Mesh from CSG taking material and transforms into account
  74038. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74039. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74040. mesh.material = material;
  74041. mesh.position.copyFrom(this.position);
  74042. mesh.rotation.copyFrom(this.rotation);
  74043. if (this.rotationQuaternion) {
  74044. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74045. }
  74046. mesh.scaling.copyFrom(this.scaling);
  74047. mesh.computeWorldMatrix(true);
  74048. return mesh;
  74049. };
  74050. return CSG;
  74051. }());
  74052. BABYLON.CSG = CSG;
  74053. })(BABYLON || (BABYLON = {}));
  74054. //# sourceMappingURL=babylon.csg.js.map
  74055. var BABYLON;
  74056. (function (BABYLON) {
  74057. var LensFlare = /** @class */ (function () {
  74058. function LensFlare(size, position, color, imgUrl, system) {
  74059. this.size = size;
  74060. this.position = position;
  74061. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74062. this.color = color || new BABYLON.Color3(1, 1, 1);
  74063. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74064. this._system = system;
  74065. system.lensFlares.push(this);
  74066. }
  74067. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74068. return new LensFlare(size, position, color, imgUrl, system);
  74069. };
  74070. LensFlare.prototype.dispose = function () {
  74071. if (this.texture) {
  74072. this.texture.dispose();
  74073. }
  74074. // Remove from scene
  74075. var index = this._system.lensFlares.indexOf(this);
  74076. this._system.lensFlares.splice(index, 1);
  74077. };
  74078. ;
  74079. return LensFlare;
  74080. }());
  74081. BABYLON.LensFlare = LensFlare;
  74082. })(BABYLON || (BABYLON = {}));
  74083. //# sourceMappingURL=babylon.lensFlare.js.map
  74084. var BABYLON;
  74085. (function (BABYLON) {
  74086. var LensFlareSystem = /** @class */ (function () {
  74087. function LensFlareSystem(name, emitter, scene) {
  74088. this.name = name;
  74089. this.lensFlares = new Array();
  74090. this.borderLimit = 300;
  74091. this.viewportBorder = 0;
  74092. this.layerMask = 0x0FFFFFFF;
  74093. this._vertexBuffers = {};
  74094. this._isEnabled = true;
  74095. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74096. this._emitter = emitter;
  74097. this.id = name;
  74098. scene.lensFlareSystems.push(this);
  74099. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74100. var engine = scene.getEngine();
  74101. // VBO
  74102. var vertices = [];
  74103. vertices.push(1, 1);
  74104. vertices.push(-1, 1);
  74105. vertices.push(-1, -1);
  74106. vertices.push(1, -1);
  74107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74108. // Indices
  74109. var indices = [];
  74110. indices.push(0);
  74111. indices.push(1);
  74112. indices.push(2);
  74113. indices.push(0);
  74114. indices.push(2);
  74115. indices.push(3);
  74116. this._indexBuffer = engine.createIndexBuffer(indices);
  74117. // Effects
  74118. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74119. }
  74120. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74121. get: function () {
  74122. return this._isEnabled;
  74123. },
  74124. set: function (value) {
  74125. this._isEnabled = value;
  74126. },
  74127. enumerable: true,
  74128. configurable: true
  74129. });
  74130. LensFlareSystem.prototype.getScene = function () {
  74131. return this._scene;
  74132. };
  74133. LensFlareSystem.prototype.getEmitter = function () {
  74134. return this._emitter;
  74135. };
  74136. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74137. this._emitter = newEmitter;
  74138. };
  74139. LensFlareSystem.prototype.getEmitterPosition = function () {
  74140. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74141. };
  74142. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74143. var position = this.getEmitterPosition();
  74144. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74145. this._positionX = position.x;
  74146. this._positionY = position.y;
  74147. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74148. if (this.viewportBorder > 0) {
  74149. globalViewport.x -= this.viewportBorder;
  74150. globalViewport.y -= this.viewportBorder;
  74151. globalViewport.width += this.viewportBorder * 2;
  74152. globalViewport.height += this.viewportBorder * 2;
  74153. position.x += this.viewportBorder;
  74154. position.y += this.viewportBorder;
  74155. this._positionX += this.viewportBorder;
  74156. this._positionY += this.viewportBorder;
  74157. }
  74158. if (position.z > 0) {
  74159. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74160. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74161. return true;
  74162. }
  74163. return true;
  74164. }
  74165. return false;
  74166. };
  74167. LensFlareSystem.prototype._isVisible = function () {
  74168. if (!this._isEnabled || !this._scene.activeCamera) {
  74169. return false;
  74170. }
  74171. var emitterPosition = this.getEmitterPosition();
  74172. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74173. var distance = direction.length();
  74174. direction.normalize();
  74175. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74176. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74177. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74178. };
  74179. LensFlareSystem.prototype.render = function () {
  74180. if (!this._effect.isReady() || !this._scene.activeCamera)
  74181. return false;
  74182. var engine = this._scene.getEngine();
  74183. var viewport = this._scene.activeCamera.viewport;
  74184. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74185. // Position
  74186. if (!this.computeEffectivePosition(globalViewport)) {
  74187. return false;
  74188. }
  74189. // Visibility
  74190. if (!this._isVisible()) {
  74191. return false;
  74192. }
  74193. // Intensity
  74194. var awayX;
  74195. var awayY;
  74196. if (this._positionX < this.borderLimit + globalViewport.x) {
  74197. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74198. }
  74199. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74200. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74201. }
  74202. else {
  74203. awayX = 0;
  74204. }
  74205. if (this._positionY < this.borderLimit + globalViewport.y) {
  74206. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74207. }
  74208. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74209. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74210. }
  74211. else {
  74212. awayY = 0;
  74213. }
  74214. var away = (awayX > awayY) ? awayX : awayY;
  74215. away -= this.viewportBorder;
  74216. if (away > this.borderLimit) {
  74217. away = this.borderLimit;
  74218. }
  74219. var intensity = 1.0 - (away / this.borderLimit);
  74220. if (intensity < 0) {
  74221. return false;
  74222. }
  74223. if (intensity > 1.0) {
  74224. intensity = 1.0;
  74225. }
  74226. if (this.viewportBorder > 0) {
  74227. globalViewport.x += this.viewportBorder;
  74228. globalViewport.y += this.viewportBorder;
  74229. globalViewport.width -= this.viewportBorder * 2;
  74230. globalViewport.height -= this.viewportBorder * 2;
  74231. this._positionX -= this.viewportBorder;
  74232. this._positionY -= this.viewportBorder;
  74233. }
  74234. // Position
  74235. var centerX = globalViewport.x + globalViewport.width / 2;
  74236. var centerY = globalViewport.y + globalViewport.height / 2;
  74237. var distX = centerX - this._positionX;
  74238. var distY = centerY - this._positionY;
  74239. // Effects
  74240. engine.enableEffect(this._effect);
  74241. engine.setState(false);
  74242. engine.setDepthBuffer(false);
  74243. // VBOs
  74244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74245. // Flares
  74246. for (var index = 0; index < this.lensFlares.length; index++) {
  74247. var flare = this.lensFlares[index];
  74248. engine.setAlphaMode(flare.alphaMode);
  74249. var x = centerX - (distX * flare.position);
  74250. var y = centerY - (distY * flare.position);
  74251. var cw = flare.size;
  74252. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74253. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74254. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74255. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74256. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74257. // Texture
  74258. this._effect.setTexture("textureSampler", flare.texture);
  74259. // Color
  74260. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74261. // Draw order
  74262. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74263. }
  74264. engine.setDepthBuffer(true);
  74265. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74266. return true;
  74267. };
  74268. LensFlareSystem.prototype.dispose = function () {
  74269. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74270. if (vertexBuffer) {
  74271. vertexBuffer.dispose();
  74272. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74273. }
  74274. if (this._indexBuffer) {
  74275. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74276. this._indexBuffer = null;
  74277. }
  74278. while (this.lensFlares.length) {
  74279. this.lensFlares[0].dispose();
  74280. }
  74281. // Remove from scene
  74282. var index = this._scene.lensFlareSystems.indexOf(this);
  74283. this._scene.lensFlareSystems.splice(index, 1);
  74284. };
  74285. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74286. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74287. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74288. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74289. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74290. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74291. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74292. var parsedFlare = parsedLensFlareSystem.flares[index];
  74293. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74294. }
  74295. return lensFlareSystem;
  74296. };
  74297. LensFlareSystem.prototype.serialize = function () {
  74298. var serializationObject = {};
  74299. serializationObject.id = this.id;
  74300. serializationObject.name = this.name;
  74301. serializationObject.emitterId = this.getEmitter().id;
  74302. serializationObject.borderLimit = this.borderLimit;
  74303. serializationObject.flares = [];
  74304. for (var index = 0; index < this.lensFlares.length; index++) {
  74305. var flare = this.lensFlares[index];
  74306. serializationObject.flares.push({
  74307. size: flare.size,
  74308. position: flare.position,
  74309. color: flare.color.asArray(),
  74310. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74311. });
  74312. }
  74313. return serializationObject;
  74314. };
  74315. return LensFlareSystem;
  74316. }());
  74317. BABYLON.LensFlareSystem = LensFlareSystem;
  74318. })(BABYLON || (BABYLON = {}));
  74319. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74320. var BABYLON;
  74321. (function (BABYLON) {
  74322. /**
  74323. * This is a holder class for the physics joint created by the physics plugin.
  74324. * It holds a set of functions to control the underlying joint.
  74325. */
  74326. var PhysicsJoint = /** @class */ (function () {
  74327. function PhysicsJoint(type, jointData) {
  74328. this.type = type;
  74329. this.jointData = jointData;
  74330. jointData.nativeParams = jointData.nativeParams || {};
  74331. }
  74332. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74333. get: function () {
  74334. return this._physicsJoint;
  74335. },
  74336. set: function (newJoint) {
  74337. if (this._physicsJoint) {
  74338. //remove from the wolrd
  74339. }
  74340. this._physicsJoint = newJoint;
  74341. },
  74342. enumerable: true,
  74343. configurable: true
  74344. });
  74345. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74346. set: function (physicsPlugin) {
  74347. this._physicsPlugin = physicsPlugin;
  74348. },
  74349. enumerable: true,
  74350. configurable: true
  74351. });
  74352. /**
  74353. * Execute a function that is physics-plugin specific.
  74354. * @param {Function} func the function that will be executed.
  74355. * It accepts two parameters: the physics world and the physics joint.
  74356. */
  74357. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74358. func(this._physicsPlugin.world, this._physicsJoint);
  74359. };
  74360. //TODO check if the native joints are the same
  74361. //Joint Types
  74362. PhysicsJoint.DistanceJoint = 0;
  74363. PhysicsJoint.HingeJoint = 1;
  74364. PhysicsJoint.BallAndSocketJoint = 2;
  74365. PhysicsJoint.WheelJoint = 3;
  74366. PhysicsJoint.SliderJoint = 4;
  74367. //OIMO
  74368. PhysicsJoint.PrismaticJoint = 5;
  74369. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74370. PhysicsJoint.UniversalJoint = 6;
  74371. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74372. //Cannon
  74373. //Similar to a Ball-Joint. Different in params
  74374. PhysicsJoint.PointToPointJoint = 8;
  74375. //Cannon only at the moment
  74376. PhysicsJoint.SpringJoint = 9;
  74377. PhysicsJoint.LockJoint = 10;
  74378. return PhysicsJoint;
  74379. }());
  74380. BABYLON.PhysicsJoint = PhysicsJoint;
  74381. /**
  74382. * A class representing a physics distance joint.
  74383. */
  74384. var DistanceJoint = /** @class */ (function (_super) {
  74385. __extends(DistanceJoint, _super);
  74386. function DistanceJoint(jointData) {
  74387. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74388. }
  74389. /**
  74390. * Update the predefined distance.
  74391. */
  74392. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74393. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74394. };
  74395. return DistanceJoint;
  74396. }(PhysicsJoint));
  74397. BABYLON.DistanceJoint = DistanceJoint;
  74398. var MotorEnabledJoint = /** @class */ (function (_super) {
  74399. __extends(MotorEnabledJoint, _super);
  74400. function MotorEnabledJoint(type, jointData) {
  74401. return _super.call(this, type, jointData) || this;
  74402. }
  74403. /**
  74404. * Set the motor values.
  74405. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74406. * @param {number} force the force to apply
  74407. * @param {number} maxForce max force for this motor.
  74408. */
  74409. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74410. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74411. };
  74412. /**
  74413. * Set the motor's limits.
  74414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74415. */
  74416. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74417. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74418. };
  74419. return MotorEnabledJoint;
  74420. }(PhysicsJoint));
  74421. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74422. /**
  74423. * This class represents a single hinge physics joint
  74424. */
  74425. var HingeJoint = /** @class */ (function (_super) {
  74426. __extends(HingeJoint, _super);
  74427. function HingeJoint(jointData) {
  74428. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74429. }
  74430. /**
  74431. * Set the motor values.
  74432. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74433. * @param {number} force the force to apply
  74434. * @param {number} maxForce max force for this motor.
  74435. */
  74436. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74437. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74438. };
  74439. /**
  74440. * Set the motor's limits.
  74441. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74442. */
  74443. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74444. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74445. };
  74446. return HingeJoint;
  74447. }(MotorEnabledJoint));
  74448. BABYLON.HingeJoint = HingeJoint;
  74449. /**
  74450. * This class represents a dual hinge physics joint (same as wheel joint)
  74451. */
  74452. var Hinge2Joint = /** @class */ (function (_super) {
  74453. __extends(Hinge2Joint, _super);
  74454. function Hinge2Joint(jointData) {
  74455. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74456. }
  74457. /**
  74458. * Set the motor values.
  74459. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74460. * @param {number} force the force to apply
  74461. * @param {number} maxForce max force for this motor.
  74462. * @param {motorIndex} the motor's index, 0 or 1.
  74463. */
  74464. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74465. if (motorIndex === void 0) { motorIndex = 0; }
  74466. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74467. };
  74468. /**
  74469. * Set the motor limits.
  74470. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74471. * @param {number} upperLimit the upper limit
  74472. * @param {number} lowerLimit lower limit
  74473. * @param {motorIndex} the motor's index, 0 or 1.
  74474. */
  74475. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74476. if (motorIndex === void 0) { motorIndex = 0; }
  74477. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74478. };
  74479. return Hinge2Joint;
  74480. }(MotorEnabledJoint));
  74481. BABYLON.Hinge2Joint = Hinge2Joint;
  74482. })(BABYLON || (BABYLON = {}));
  74483. //# sourceMappingURL=babylon.physicsJoint.js.map
  74484. var BABYLON;
  74485. (function (BABYLON) {
  74486. var PhysicsImpostor = /** @class */ (function () {
  74487. function PhysicsImpostor(object, type, _options, _scene) {
  74488. if (_options === void 0) { _options = { mass: 0 }; }
  74489. var _this = this;
  74490. this.object = object;
  74491. this.type = type;
  74492. this._options = _options;
  74493. this._scene = _scene;
  74494. this._bodyUpdateRequired = false;
  74495. this._onBeforePhysicsStepCallbacks = new Array();
  74496. this._onAfterPhysicsStepCallbacks = new Array();
  74497. this._onPhysicsCollideCallbacks = [];
  74498. this._deltaPosition = BABYLON.Vector3.Zero();
  74499. this._isDisposed = false;
  74500. //temp variables for parent rotation calculations
  74501. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74502. this._tmpQuat = new BABYLON.Quaternion();
  74503. this._tmpQuat2 = new BABYLON.Quaternion();
  74504. /**
  74505. * this function is executed by the physics engine.
  74506. */
  74507. this.beforeStep = function () {
  74508. if (!_this._physicsEngine) {
  74509. return;
  74510. }
  74511. _this.object.translate(_this._deltaPosition, -1);
  74512. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74513. _this.object.computeWorldMatrix(false);
  74514. if (_this.object.parent && _this.object.rotationQuaternion) {
  74515. _this.getParentsRotation();
  74516. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74517. }
  74518. else {
  74519. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74520. }
  74521. if (!_this._options.disableBidirectionalTransformation) {
  74522. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74523. }
  74524. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74525. func(_this);
  74526. });
  74527. };
  74528. /**
  74529. * this function is executed by the physics engine.
  74530. */
  74531. this.afterStep = function () {
  74532. if (!_this._physicsEngine) {
  74533. return;
  74534. }
  74535. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74536. func(_this);
  74537. });
  74538. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74539. // object has now its world rotation. needs to be converted to local.
  74540. if (_this.object.parent && _this.object.rotationQuaternion) {
  74541. _this.getParentsRotation();
  74542. _this._tmpQuat.conjugateInPlace();
  74543. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74544. }
  74545. // take the position set and make it the absolute position of this object.
  74546. _this.object.setAbsolutePosition(_this.object.position);
  74547. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74548. _this.object.translate(_this._deltaPosition, 1);
  74549. };
  74550. /**
  74551. * Legacy collision detection event support
  74552. */
  74553. this.onCollideEvent = null;
  74554. //event and body object due to cannon's event-based architecture.
  74555. this.onCollide = function (e) {
  74556. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74557. return;
  74558. }
  74559. if (!_this._physicsEngine) {
  74560. return;
  74561. }
  74562. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74563. if (otherImpostor) {
  74564. // Legacy collision detection event support
  74565. if (_this.onCollideEvent) {
  74566. _this.onCollideEvent(_this, otherImpostor);
  74567. }
  74568. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74569. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74570. }).forEach(function (obj) {
  74571. obj.callback(_this, otherImpostor);
  74572. });
  74573. }
  74574. };
  74575. //sanity check!
  74576. if (!this.object) {
  74577. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74578. return;
  74579. }
  74580. //legacy support for old syntax.
  74581. if (!this._scene && object.getScene) {
  74582. this._scene = object.getScene();
  74583. }
  74584. if (!this._scene) {
  74585. return;
  74586. }
  74587. this._physicsEngine = this._scene.getPhysicsEngine();
  74588. if (!this._physicsEngine) {
  74589. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74590. }
  74591. else {
  74592. //set the object's quaternion, if not set
  74593. if (!this.object.rotationQuaternion) {
  74594. if (this.object.rotation) {
  74595. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74596. }
  74597. else {
  74598. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74599. }
  74600. }
  74601. //default options params
  74602. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74603. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74604. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74605. this._joints = [];
  74606. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74607. if (!this.object.parent || this._options.ignoreParent) {
  74608. this._init();
  74609. }
  74610. else if (this.object.parent.physicsImpostor) {
  74611. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74612. }
  74613. }
  74614. }
  74615. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74616. get: function () {
  74617. return this._isDisposed;
  74618. },
  74619. enumerable: true,
  74620. configurable: true
  74621. });
  74622. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74623. get: function () {
  74624. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74625. },
  74626. set: function (value) {
  74627. this.setMass(value);
  74628. },
  74629. enumerable: true,
  74630. configurable: true
  74631. });
  74632. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74633. get: function () {
  74634. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74635. },
  74636. set: function (value) {
  74637. if (!this._physicsEngine) {
  74638. return;
  74639. }
  74640. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74641. },
  74642. enumerable: true,
  74643. configurable: true
  74644. });
  74645. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74646. get: function () {
  74647. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74648. },
  74649. set: function (value) {
  74650. if (!this._physicsEngine) {
  74651. return;
  74652. }
  74653. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74654. },
  74655. enumerable: true,
  74656. configurable: true
  74657. });
  74658. /**
  74659. * This function will completly initialize this impostor.
  74660. * It will create a new body - but only if this mesh has no parent.
  74661. * If it has, this impostor will not be used other than to define the impostor
  74662. * of the child mesh.
  74663. */
  74664. PhysicsImpostor.prototype._init = function () {
  74665. if (!this._physicsEngine) {
  74666. return;
  74667. }
  74668. this._physicsEngine.removeImpostor(this);
  74669. this.physicsBody = null;
  74670. this._parent = this._parent || this._getPhysicsParent();
  74671. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74672. this._physicsEngine.addImpostor(this);
  74673. }
  74674. };
  74675. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74676. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74677. var parentMesh = this.object.parent;
  74678. return parentMesh.physicsImpostor;
  74679. }
  74680. return null;
  74681. };
  74682. /**
  74683. * Should a new body be generated.
  74684. */
  74685. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74686. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74687. };
  74688. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74689. this.forceUpdate();
  74690. };
  74691. /**
  74692. * Force a regeneration of this or the parent's impostor's body.
  74693. * Use under cautious - This will remove all joints already implemented.
  74694. */
  74695. PhysicsImpostor.prototype.forceUpdate = function () {
  74696. this._init();
  74697. if (this.parent && !this._options.ignoreParent) {
  74698. this.parent.forceUpdate();
  74699. }
  74700. };
  74701. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74702. /*public get mesh(): AbstractMesh {
  74703. return this._mesh;
  74704. }*/
  74705. /**
  74706. * Gets the body that holds this impostor. Either its own, or its parent.
  74707. */
  74708. get: function () {
  74709. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74710. },
  74711. /**
  74712. * Set the physics body. Used mainly by the physics engine/plugin
  74713. */
  74714. set: function (physicsBody) {
  74715. if (this._physicsBody && this._physicsEngine) {
  74716. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74717. }
  74718. this._physicsBody = physicsBody;
  74719. this.resetUpdateFlags();
  74720. },
  74721. enumerable: true,
  74722. configurable: true
  74723. });
  74724. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74725. get: function () {
  74726. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74727. },
  74728. set: function (value) {
  74729. this._parent = value;
  74730. },
  74731. enumerable: true,
  74732. configurable: true
  74733. });
  74734. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74735. this._bodyUpdateRequired = false;
  74736. };
  74737. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74738. if (this.object.getBoundingInfo) {
  74739. var q = this.object.rotationQuaternion;
  74740. //reset rotation
  74741. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74742. //calculate the world matrix with no rotation
  74743. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74744. var boundingInfo = this.object.getBoundingInfo();
  74745. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74746. //bring back the rotation
  74747. this.object.rotationQuaternion = q;
  74748. //calculate the world matrix with the new rotation
  74749. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74750. return size;
  74751. }
  74752. else {
  74753. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74754. }
  74755. };
  74756. PhysicsImpostor.prototype.getObjectCenter = function () {
  74757. if (this.object.getBoundingInfo) {
  74758. var boundingInfo = this.object.getBoundingInfo();
  74759. return boundingInfo.boundingBox.centerWorld;
  74760. }
  74761. else {
  74762. return this.object.position;
  74763. }
  74764. };
  74765. /**
  74766. * Get a specific parametes from the options parameter.
  74767. */
  74768. PhysicsImpostor.prototype.getParam = function (paramName) {
  74769. return this._options[paramName];
  74770. };
  74771. /**
  74772. * Sets a specific parameter in the options given to the physics plugin
  74773. */
  74774. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74775. this._options[paramName] = value;
  74776. this._bodyUpdateRequired = true;
  74777. };
  74778. /**
  74779. * Specifically change the body's mass option. Won't recreate the physics body object
  74780. */
  74781. PhysicsImpostor.prototype.setMass = function (mass) {
  74782. if (this.getParam("mass") !== mass) {
  74783. this.setParam("mass", mass);
  74784. }
  74785. if (this._physicsEngine) {
  74786. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74787. }
  74788. };
  74789. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74790. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74791. };
  74792. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74793. if (this._physicsEngine) {
  74794. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74795. }
  74796. };
  74797. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74798. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74799. };
  74800. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74801. if (this._physicsEngine) {
  74802. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74803. }
  74804. };
  74805. /**
  74806. * Execute a function with the physics plugin native code.
  74807. * Provide a function the will have two variables - the world object and the physics body object.
  74808. */
  74809. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74810. if (this._physicsEngine) {
  74811. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74812. }
  74813. };
  74814. /**
  74815. * Register a function that will be executed before the physics world is stepping forward.
  74816. */
  74817. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74818. this._onBeforePhysicsStepCallbacks.push(func);
  74819. };
  74820. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74821. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74822. if (index > -1) {
  74823. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74824. }
  74825. else {
  74826. BABYLON.Tools.Warn("Function to remove was not found");
  74827. }
  74828. };
  74829. /**
  74830. * Register a function that will be executed after the physics step
  74831. */
  74832. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74833. this._onAfterPhysicsStepCallbacks.push(func);
  74834. };
  74835. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74836. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74837. if (index > -1) {
  74838. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74839. }
  74840. else {
  74841. BABYLON.Tools.Warn("Function to remove was not found");
  74842. }
  74843. };
  74844. /**
  74845. * register a function that will be executed when this impostor collides against a different body.
  74846. */
  74847. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74848. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74849. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74850. };
  74851. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74852. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74853. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74854. if (index > -1) {
  74855. this._onPhysicsCollideCallbacks.splice(index, 1);
  74856. }
  74857. else {
  74858. BABYLON.Tools.Warn("Function to remove was not found");
  74859. }
  74860. };
  74861. PhysicsImpostor.prototype.getParentsRotation = function () {
  74862. var parent = this.object.parent;
  74863. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74864. while (parent) {
  74865. if (parent.rotationQuaternion) {
  74866. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74867. }
  74868. else {
  74869. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74870. }
  74871. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74872. parent = parent.parent;
  74873. }
  74874. return this._tmpQuat;
  74875. };
  74876. /**
  74877. * Apply a force
  74878. */
  74879. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74880. if (this._physicsEngine) {
  74881. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74882. }
  74883. return this;
  74884. };
  74885. /**
  74886. * Apply an impulse
  74887. */
  74888. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74889. if (this._physicsEngine) {
  74890. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74891. }
  74892. return this;
  74893. };
  74894. /**
  74895. * A help function to create a joint.
  74896. */
  74897. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74898. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74899. this.addJoint(otherImpostor, joint);
  74900. return this;
  74901. };
  74902. /**
  74903. * Add a joint to this impostor with a different impostor.
  74904. */
  74905. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74906. this._joints.push({
  74907. otherImpostor: otherImpostor,
  74908. joint: joint
  74909. });
  74910. if (this._physicsEngine) {
  74911. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74912. }
  74913. return this;
  74914. };
  74915. /**
  74916. * Will keep this body still, in a sleep mode.
  74917. */
  74918. PhysicsImpostor.prototype.sleep = function () {
  74919. if (this._physicsEngine) {
  74920. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74921. }
  74922. return this;
  74923. };
  74924. /**
  74925. * Wake the body up.
  74926. */
  74927. PhysicsImpostor.prototype.wakeUp = function () {
  74928. if (this._physicsEngine) {
  74929. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74930. }
  74931. return this;
  74932. };
  74933. PhysicsImpostor.prototype.clone = function (newObject) {
  74934. if (!newObject)
  74935. return null;
  74936. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74937. };
  74938. PhysicsImpostor.prototype.dispose = function () {
  74939. var _this = this;
  74940. //no dispose if no physics engine is available.
  74941. if (!this._physicsEngine) {
  74942. return;
  74943. }
  74944. this._joints.forEach(function (j) {
  74945. if (_this._physicsEngine) {
  74946. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  74947. }
  74948. });
  74949. //dispose the physics body
  74950. this._physicsEngine.removeImpostor(this);
  74951. if (this.parent) {
  74952. this.parent.forceUpdate();
  74953. }
  74954. else {
  74955. /*this._object.getChildMeshes().forEach(function(mesh) {
  74956. if (mesh.physicsImpostor) {
  74957. if (disposeChildren) {
  74958. mesh.physicsImpostor.dispose();
  74959. mesh.physicsImpostor = null;
  74960. }
  74961. }
  74962. })*/
  74963. }
  74964. this._isDisposed = true;
  74965. };
  74966. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  74967. this._deltaPosition.copyFrom(position);
  74968. };
  74969. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  74970. if (!this._deltaRotation) {
  74971. this._deltaRotation = new BABYLON.Quaternion();
  74972. }
  74973. this._deltaRotation.copyFrom(rotation);
  74974. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  74975. };
  74976. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  74977. if (this._physicsEngine) {
  74978. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  74979. }
  74980. return this;
  74981. };
  74982. PhysicsImpostor.prototype.getRadius = function () {
  74983. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  74984. };
  74985. /**
  74986. * Sync a bone with this impostor
  74987. * @param bone The bone to sync to the impostor.
  74988. * @param boneMesh The mesh that the bone is influencing.
  74989. * @param jointPivot The pivot of the joint / bone in local space.
  74990. * @param distToJoint Optional distance from the impostor to the joint.
  74991. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74992. */
  74993. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  74994. var tempVec = PhysicsImpostor._tmpVecs[0];
  74995. var mesh = this.object;
  74996. if (mesh.rotationQuaternion) {
  74997. if (adjustRotation) {
  74998. var tempQuat = PhysicsImpostor._tmpQuat;
  74999. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75000. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75001. }
  75002. else {
  75003. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75004. }
  75005. }
  75006. tempVec.x = 0;
  75007. tempVec.y = 0;
  75008. tempVec.z = 0;
  75009. if (jointPivot) {
  75010. tempVec.x = jointPivot.x;
  75011. tempVec.y = jointPivot.y;
  75012. tempVec.z = jointPivot.z;
  75013. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75014. if (distToJoint === undefined || distToJoint === null) {
  75015. distToJoint = jointPivot.length();
  75016. }
  75017. tempVec.x *= distToJoint;
  75018. tempVec.y *= distToJoint;
  75019. tempVec.z *= distToJoint;
  75020. }
  75021. if (bone.getParent()) {
  75022. tempVec.addInPlace(mesh.getAbsolutePosition());
  75023. bone.setAbsolutePosition(tempVec, boneMesh);
  75024. }
  75025. else {
  75026. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75027. boneMesh.position.x -= tempVec.x;
  75028. boneMesh.position.y -= tempVec.y;
  75029. boneMesh.position.z -= tempVec.z;
  75030. }
  75031. };
  75032. /**
  75033. * Sync impostor to a bone
  75034. * @param bone The bone that the impostor will be synced to.
  75035. * @param boneMesh The mesh that the bone is influencing.
  75036. * @param jointPivot The pivot of the joint / bone in local space.
  75037. * @param distToJoint Optional distance from the impostor to the joint.
  75038. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75039. * @param boneAxis Optional vector3 axis the bone is aligned with
  75040. */
  75041. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75042. var mesh = this.object;
  75043. if (mesh.rotationQuaternion) {
  75044. if (adjustRotation) {
  75045. var tempQuat = PhysicsImpostor._tmpQuat;
  75046. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75047. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75048. }
  75049. else {
  75050. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75051. }
  75052. }
  75053. var pos = PhysicsImpostor._tmpVecs[0];
  75054. var boneDir = PhysicsImpostor._tmpVecs[1];
  75055. if (!boneAxis) {
  75056. boneAxis = PhysicsImpostor._tmpVecs[2];
  75057. boneAxis.x = 0;
  75058. boneAxis.y = 1;
  75059. boneAxis.z = 0;
  75060. }
  75061. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75062. bone.getAbsolutePositionToRef(boneMesh, pos);
  75063. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75064. distToJoint = jointPivot.length();
  75065. }
  75066. if (distToJoint !== undefined && distToJoint !== null) {
  75067. pos.x += boneDir.x * distToJoint;
  75068. pos.y += boneDir.y * distToJoint;
  75069. pos.z += boneDir.z * distToJoint;
  75070. }
  75071. mesh.setAbsolutePosition(pos);
  75072. };
  75073. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75074. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75075. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75076. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75077. //Impostor types
  75078. PhysicsImpostor.NoImpostor = 0;
  75079. PhysicsImpostor.SphereImpostor = 1;
  75080. PhysicsImpostor.BoxImpostor = 2;
  75081. PhysicsImpostor.PlaneImpostor = 3;
  75082. PhysicsImpostor.MeshImpostor = 4;
  75083. PhysicsImpostor.CylinderImpostor = 7;
  75084. PhysicsImpostor.ParticleImpostor = 8;
  75085. PhysicsImpostor.HeightmapImpostor = 9;
  75086. return PhysicsImpostor;
  75087. }());
  75088. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75089. })(BABYLON || (BABYLON = {}));
  75090. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75091. var BABYLON;
  75092. (function (BABYLON) {
  75093. var PhysicsEngine = /** @class */ (function () {
  75094. function PhysicsEngine(gravity, _physicsPlugin) {
  75095. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75096. this._physicsPlugin = _physicsPlugin;
  75097. //new methods and parameters
  75098. this._impostors = [];
  75099. this._joints = [];
  75100. if (!this._physicsPlugin.isSupported()) {
  75101. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75102. + "Please make sure it is included.");
  75103. }
  75104. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75105. this.setGravity(gravity);
  75106. this.setTimeStep();
  75107. }
  75108. PhysicsEngine.prototype.setGravity = function (gravity) {
  75109. this.gravity = gravity;
  75110. this._physicsPlugin.setGravity(this.gravity);
  75111. };
  75112. /**
  75113. * Set the time step of the physics engine.
  75114. * default is 1/60.
  75115. * To slow it down, enter 1/600 for example.
  75116. * To speed it up, 1/30
  75117. * @param {number} newTimeStep the new timestep to apply to this world.
  75118. */
  75119. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75120. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75121. this._physicsPlugin.setTimeStep(newTimeStep);
  75122. };
  75123. /**
  75124. * Get the time step of the physics engine.
  75125. */
  75126. PhysicsEngine.prototype.getTimeStep = function () {
  75127. return this._physicsPlugin.getTimeStep();
  75128. };
  75129. PhysicsEngine.prototype.dispose = function () {
  75130. this._impostors.forEach(function (impostor) {
  75131. impostor.dispose();
  75132. });
  75133. this._physicsPlugin.dispose();
  75134. };
  75135. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75136. return this._physicsPlugin.name;
  75137. };
  75138. /**
  75139. * Adding a new impostor for the impostor tracking.
  75140. * This will be done by the impostor itself.
  75141. * @param {PhysicsImpostor} impostor the impostor to add
  75142. */
  75143. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75144. impostor.uniqueId = this._impostors.push(impostor);
  75145. //if no parent, generate the body
  75146. if (!impostor.parent) {
  75147. this._physicsPlugin.generatePhysicsBody(impostor);
  75148. }
  75149. };
  75150. /**
  75151. * Remove an impostor from the engine.
  75152. * This impostor and its mesh will not longer be updated by the physics engine.
  75153. * @param {PhysicsImpostor} impostor the impostor to remove
  75154. */
  75155. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75156. var index = this._impostors.indexOf(impostor);
  75157. if (index > -1) {
  75158. var removed = this._impostors.splice(index, 1);
  75159. //Is it needed?
  75160. if (removed.length) {
  75161. //this will also remove it from the world.
  75162. removed[0].physicsBody = null;
  75163. }
  75164. }
  75165. };
  75166. /**
  75167. * Add a joint to the physics engine
  75168. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75169. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75170. * @param {PhysicsJoint} the joint that will connect both impostors.
  75171. */
  75172. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75173. var impostorJoint = {
  75174. mainImpostor: mainImpostor,
  75175. connectedImpostor: connectedImpostor,
  75176. joint: joint
  75177. };
  75178. joint.physicsPlugin = this._physicsPlugin;
  75179. this._joints.push(impostorJoint);
  75180. this._physicsPlugin.generateJoint(impostorJoint);
  75181. };
  75182. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75183. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75184. return (impostorJoint.connectedImpostor === connectedImpostor
  75185. && impostorJoint.joint === joint
  75186. && impostorJoint.mainImpostor === mainImpostor);
  75187. });
  75188. if (matchingJoints.length) {
  75189. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75190. //TODO remove it from the list as well
  75191. }
  75192. };
  75193. /**
  75194. * Called by the scene. no need to call it.
  75195. */
  75196. PhysicsEngine.prototype._step = function (delta) {
  75197. var _this = this;
  75198. //check if any mesh has no body / requires an update
  75199. this._impostors.forEach(function (impostor) {
  75200. if (impostor.isBodyInitRequired()) {
  75201. _this._physicsPlugin.generatePhysicsBody(impostor);
  75202. }
  75203. });
  75204. if (delta > 0.1) {
  75205. delta = 0.1;
  75206. }
  75207. else if (delta <= 0) {
  75208. delta = 1.0 / 60.0;
  75209. }
  75210. this._physicsPlugin.executeStep(delta, this._impostors);
  75211. };
  75212. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75213. return this._physicsPlugin;
  75214. };
  75215. PhysicsEngine.prototype.getImpostors = function () {
  75216. return this._impostors;
  75217. };
  75218. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75219. for (var i = 0; i < this._impostors.length; ++i) {
  75220. if (this._impostors[i].object === object) {
  75221. return this._impostors[i];
  75222. }
  75223. }
  75224. return null;
  75225. };
  75226. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75227. for (var i = 0; i < this._impostors.length; ++i) {
  75228. if (this._impostors[i].physicsBody === body) {
  75229. return this._impostors[i];
  75230. }
  75231. }
  75232. return null;
  75233. };
  75234. // Statics
  75235. PhysicsEngine.Epsilon = 0.001;
  75236. return PhysicsEngine;
  75237. }());
  75238. BABYLON.PhysicsEngine = PhysicsEngine;
  75239. })(BABYLON || (BABYLON = {}));
  75240. //# sourceMappingURL=babylon.physicsEngine.js.map
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. var PhysicsHelper = /** @class */ (function () {
  75244. function PhysicsHelper(scene) {
  75245. this._scene = scene;
  75246. this._physicsEngine = this._scene.getPhysicsEngine();
  75247. if (!this._physicsEngine) {
  75248. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75249. }
  75250. }
  75251. /**
  75252. * @param {Vector3} origin the origin of the explosion
  75253. * @param {number} radius the explosion radius
  75254. * @param {number} strength the explosion strength
  75255. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75256. */
  75257. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75258. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75259. if (!this._physicsEngine) {
  75260. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75261. return null;
  75262. }
  75263. var impostors = this._physicsEngine.getImpostors();
  75264. if (impostors.length === 0) {
  75265. return null;
  75266. }
  75267. var event = new PhysicsRadialExplosionEvent(this._scene);
  75268. impostors.forEach(function (impostor) {
  75269. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75270. if (!impostorForceAndContactPoint) {
  75271. return;
  75272. }
  75273. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75274. });
  75275. event.dispose(false);
  75276. return event;
  75277. };
  75278. /**
  75279. * @param {Vector3} origin the origin of the explosion
  75280. * @param {number} radius the explosion radius
  75281. * @param {number} strength the explosion strength
  75282. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75283. */
  75284. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75285. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75286. if (!this._physicsEngine) {
  75287. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75288. return null;
  75289. }
  75290. var impostors = this._physicsEngine.getImpostors();
  75291. if (impostors.length === 0) {
  75292. return null;
  75293. }
  75294. var event = new PhysicsRadialExplosionEvent(this._scene);
  75295. impostors.forEach(function (impostor) {
  75296. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75297. if (!impostorForceAndContactPoint) {
  75298. return;
  75299. }
  75300. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75301. });
  75302. event.dispose(false);
  75303. return event;
  75304. };
  75305. /**
  75306. * @param {Vector3} origin the origin of the explosion
  75307. * @param {number} radius the explosion radius
  75308. * @param {number} strength the explosion strength
  75309. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75310. */
  75311. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75312. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75313. if (!this._physicsEngine) {
  75314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75315. return null;
  75316. }
  75317. var impostors = this._physicsEngine.getImpostors();
  75318. if (impostors.length === 0) {
  75319. return null;
  75320. }
  75321. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75322. event.dispose(false);
  75323. return event;
  75324. };
  75325. /**
  75326. * @param {Vector3} origin the origin of the updraft
  75327. * @param {number} radius the radius of the updraft
  75328. * @param {number} strength the strength of the updraft
  75329. * @param {number} height the height of the updraft
  75330. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75331. */
  75332. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75333. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75334. if (!this._physicsEngine) {
  75335. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75336. return null;
  75337. }
  75338. if (this._physicsEngine.getImpostors().length === 0) {
  75339. return null;
  75340. }
  75341. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75342. event.dispose(false);
  75343. return event;
  75344. };
  75345. /**
  75346. * @param {Vector3} origin the of the vortex
  75347. * @param {number} radius the radius of the vortex
  75348. * @param {number} strength the strength of the vortex
  75349. * @param {number} height the height of the vortex
  75350. */
  75351. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75352. if (!this._physicsEngine) {
  75353. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75354. return null;
  75355. }
  75356. if (this._physicsEngine.getImpostors().length === 0) {
  75357. return null;
  75358. }
  75359. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75360. event.dispose(false);
  75361. return event;
  75362. };
  75363. return PhysicsHelper;
  75364. }());
  75365. BABYLON.PhysicsHelper = PhysicsHelper;
  75366. /***** Radial explosion *****/
  75367. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75368. function PhysicsRadialExplosionEvent(scene) {
  75369. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75370. this._rays = [];
  75371. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75372. this._scene = scene;
  75373. }
  75374. /**
  75375. * Returns the data related to the radial explosion event (sphere & rays).
  75376. * @returns {PhysicsRadialExplosionEventData}
  75377. */
  75378. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75379. this._dataFetched = true;
  75380. return {
  75381. sphere: this._sphere,
  75382. rays: this._rays,
  75383. };
  75384. };
  75385. /**
  75386. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75387. * @param impostor
  75388. * @param {Vector3} origin the origin of the explosion
  75389. * @param {number} radius the explosion radius
  75390. * @param {number} strength the explosion strength
  75391. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75392. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75393. */
  75394. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75395. if (impostor.mass === 0) {
  75396. return null;
  75397. }
  75398. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75399. return null;
  75400. }
  75401. if (impostor.object.getClassName() !== 'Mesh') {
  75402. return null;
  75403. }
  75404. var impostorObject = impostor.object;
  75405. var impostorObjectCenter = impostor.getObjectCenter();
  75406. var direction = impostorObjectCenter.subtract(origin);
  75407. var ray = new BABYLON.Ray(origin, direction, radius);
  75408. this._rays.push(ray);
  75409. var hit = ray.intersectsMesh(impostorObject);
  75410. var contactPoint = hit.pickedPoint;
  75411. if (!contactPoint) {
  75412. return null;
  75413. }
  75414. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75415. if (distanceFromOrigin > radius) {
  75416. return null;
  75417. }
  75418. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75419. ? strength
  75420. : strength * (1 - (distanceFromOrigin / radius));
  75421. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75422. return { force: force, contactPoint: contactPoint };
  75423. };
  75424. /**
  75425. * Disposes the sphere.
  75426. * @param {bolean} force
  75427. */
  75428. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75429. var _this = this;
  75430. if (force === void 0) { force = true; }
  75431. if (force) {
  75432. this._sphere.dispose();
  75433. }
  75434. else {
  75435. setTimeout(function () {
  75436. if (!_this._dataFetched) {
  75437. _this._sphere.dispose();
  75438. }
  75439. }, 0);
  75440. }
  75441. };
  75442. /*** Helpers ***/
  75443. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75444. if (!this._sphere) {
  75445. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75446. this._sphere.isVisible = false;
  75447. }
  75448. };
  75449. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75450. var impostorObject = impostor.object;
  75451. this._prepareSphere();
  75452. this._sphere.position = origin;
  75453. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75454. this._sphere._updateBoundingInfo();
  75455. this._sphere.computeWorldMatrix(true);
  75456. return this._sphere.intersectsMesh(impostorObject, true);
  75457. };
  75458. return PhysicsRadialExplosionEvent;
  75459. }());
  75460. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75461. /***** Gravitational Field *****/
  75462. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75463. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75464. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75465. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75466. this._physicsHelper = physicsHelper;
  75467. this._scene = scene;
  75468. this._origin = origin;
  75469. this._radius = radius;
  75470. this._strength = strength;
  75471. this._falloff = falloff;
  75472. this._tickCallback = this._tick.bind(this);
  75473. }
  75474. /**
  75475. * Returns the data related to the gravitational field event (sphere).
  75476. * @returns {PhysicsGravitationalFieldEventData}
  75477. */
  75478. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75479. this._dataFetched = true;
  75480. return {
  75481. sphere: this._sphere,
  75482. };
  75483. };
  75484. /**
  75485. * Enables the gravitational field.
  75486. */
  75487. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75488. this._tickCallback.call(this);
  75489. this._scene.registerBeforeRender(this._tickCallback);
  75490. };
  75491. /**
  75492. * Disables the gravitational field.
  75493. */
  75494. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75495. this._scene.unregisterBeforeRender(this._tickCallback);
  75496. };
  75497. /**
  75498. * Disposes the sphere.
  75499. * @param {bolean} force
  75500. */
  75501. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75502. var _this = this;
  75503. if (force === void 0) { force = true; }
  75504. if (force) {
  75505. this._sphere.dispose();
  75506. }
  75507. else {
  75508. setTimeout(function () {
  75509. if (!_this._dataFetched) {
  75510. _this._sphere.dispose();
  75511. }
  75512. }, 0);
  75513. }
  75514. };
  75515. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75516. // Since the params won't change, we fetch the event only once
  75517. if (this._sphere) {
  75518. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75519. }
  75520. else {
  75521. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75522. if (radialExplosionEvent) {
  75523. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75524. }
  75525. }
  75526. };
  75527. return PhysicsGravitationalFieldEvent;
  75528. }());
  75529. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75530. /***** Updraft *****/
  75531. var PhysicsUpdraftEvent = /** @class */ (function () {
  75532. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75533. this._scene = _scene;
  75534. this._origin = _origin;
  75535. this._radius = _radius;
  75536. this._strength = _strength;
  75537. this._height = _height;
  75538. this._updraftMode = _updraftMode;
  75539. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75540. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75541. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75542. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75543. this._physicsEngine = this._scene.getPhysicsEngine();
  75544. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75545. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75546. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75547. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75548. }
  75549. this._tickCallback = this._tick.bind(this);
  75550. }
  75551. /**
  75552. * Returns the data related to the updraft event (cylinder).
  75553. * @returns {PhysicsUpdraftEventData}
  75554. */
  75555. PhysicsUpdraftEvent.prototype.getData = function () {
  75556. this._dataFetched = true;
  75557. return {
  75558. cylinder: this._cylinder,
  75559. };
  75560. };
  75561. /**
  75562. * Enables the updraft.
  75563. */
  75564. PhysicsUpdraftEvent.prototype.enable = function () {
  75565. this._tickCallback.call(this);
  75566. this._scene.registerBeforeRender(this._tickCallback);
  75567. };
  75568. /**
  75569. * Disables the cortex.
  75570. */
  75571. PhysicsUpdraftEvent.prototype.disable = function () {
  75572. this._scene.unregisterBeforeRender(this._tickCallback);
  75573. };
  75574. /**
  75575. * Disposes the sphere.
  75576. * @param {bolean} force
  75577. */
  75578. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75579. var _this = this;
  75580. if (force === void 0) { force = true; }
  75581. if (force) {
  75582. this._cylinder.dispose();
  75583. }
  75584. else {
  75585. setTimeout(function () {
  75586. if (!_this._dataFetched) {
  75587. _this._cylinder.dispose();
  75588. }
  75589. }, 0);
  75590. }
  75591. };
  75592. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75593. if (impostor.mass === 0) {
  75594. return null;
  75595. }
  75596. if (!this._intersectsWithCylinder(impostor)) {
  75597. return null;
  75598. }
  75599. var impostorObjectCenter = impostor.getObjectCenter();
  75600. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75601. var direction = this._originDirection;
  75602. }
  75603. else {
  75604. var direction = impostorObjectCenter.subtract(this._originTop);
  75605. }
  75606. var multiplier = this._strength * -1;
  75607. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75608. return { force: force, contactPoint: impostorObjectCenter };
  75609. };
  75610. PhysicsUpdraftEvent.prototype._tick = function () {
  75611. var _this = this;
  75612. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75613. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75614. if (!impostorForceAndContactPoint) {
  75615. return;
  75616. }
  75617. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75618. });
  75619. };
  75620. /*** Helpers ***/
  75621. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75622. if (!this._cylinder) {
  75623. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75624. height: this._height,
  75625. diameter: this._radius * 2,
  75626. }, this._scene);
  75627. this._cylinder.isVisible = false;
  75628. }
  75629. };
  75630. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75631. var impostorObject = impostor.object;
  75632. this._prepareCylinder();
  75633. this._cylinder.position = this._cylinderPosition;
  75634. return this._cylinder.intersectsMesh(impostorObject, true);
  75635. };
  75636. return PhysicsUpdraftEvent;
  75637. }());
  75638. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75639. /***** Vortex *****/
  75640. var PhysicsVortexEvent = /** @class */ (function () {
  75641. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75642. this._scene = _scene;
  75643. this._origin = _origin;
  75644. this._radius = _radius;
  75645. this._strength = _strength;
  75646. this._height = _height;
  75647. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75648. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75649. this._updraftMultiplier = 0.02;
  75650. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75651. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75652. this._physicsEngine = this._scene.getPhysicsEngine();
  75653. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75654. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75655. this._tickCallback = this._tick.bind(this);
  75656. }
  75657. /**
  75658. * Returns the data related to the vortex event (cylinder).
  75659. * @returns {PhysicsVortexEventData}
  75660. */
  75661. PhysicsVortexEvent.prototype.getData = function () {
  75662. this._dataFetched = true;
  75663. return {
  75664. cylinder: this._cylinder,
  75665. };
  75666. };
  75667. /**
  75668. * Enables the vortex.
  75669. */
  75670. PhysicsVortexEvent.prototype.enable = function () {
  75671. this._tickCallback.call(this);
  75672. this._scene.registerBeforeRender(this._tickCallback);
  75673. };
  75674. /**
  75675. * Disables the cortex.
  75676. */
  75677. PhysicsVortexEvent.prototype.disable = function () {
  75678. this._scene.unregisterBeforeRender(this._tickCallback);
  75679. };
  75680. /**
  75681. * Disposes the sphere.
  75682. * @param {bolean} force
  75683. */
  75684. PhysicsVortexEvent.prototype.dispose = function (force) {
  75685. var _this = this;
  75686. if (force === void 0) { force = true; }
  75687. if (force) {
  75688. this._cylinder.dispose();
  75689. }
  75690. else {
  75691. setTimeout(function () {
  75692. if (!_this._dataFetched) {
  75693. _this._cylinder.dispose();
  75694. }
  75695. }, 0);
  75696. }
  75697. };
  75698. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75699. if (impostor.mass === 0) {
  75700. return null;
  75701. }
  75702. if (!this._intersectsWithCylinder(impostor)) {
  75703. return null;
  75704. }
  75705. if (impostor.object.getClassName() !== 'Mesh') {
  75706. return null;
  75707. }
  75708. var impostorObject = impostor.object;
  75709. var impostorObjectCenter = impostor.getObjectCenter();
  75710. 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)
  75711. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75712. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75713. var hit = ray.intersectsMesh(impostorObject);
  75714. var contactPoint = hit.pickedPoint;
  75715. if (!contactPoint) {
  75716. return null;
  75717. }
  75718. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75719. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75720. var directionToOrigin = contactPoint.normalize();
  75721. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75722. directionToOrigin = directionToOrigin.negate();
  75723. }
  75724. // TODO: find a more physically based solution
  75725. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75726. var forceX = directionToOrigin.x * this._strength / 8;
  75727. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75728. var forceZ = directionToOrigin.z * this._strength / 8;
  75729. }
  75730. else {
  75731. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75732. var forceY = this._originTop.y * this._updraftMultiplier;
  75733. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75734. }
  75735. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75736. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75737. return { force: force, contactPoint: impostorObjectCenter };
  75738. };
  75739. PhysicsVortexEvent.prototype._tick = function () {
  75740. var _this = this;
  75741. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75742. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75743. if (!impostorForceAndContactPoint) {
  75744. return;
  75745. }
  75746. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75747. });
  75748. };
  75749. /*** Helpers ***/
  75750. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75751. if (!this._cylinder) {
  75752. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75753. height: this._height,
  75754. diameter: this._radius * 2,
  75755. }, this._scene);
  75756. this._cylinder.isVisible = false;
  75757. }
  75758. };
  75759. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75760. var impostorObject = impostor.object;
  75761. this._prepareCylinder();
  75762. this._cylinder.position = this._cylinderPosition;
  75763. return this._cylinder.intersectsMesh(impostorObject, true);
  75764. };
  75765. return PhysicsVortexEvent;
  75766. }());
  75767. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75768. /***** Enums *****/
  75769. /**
  75770. * The strenght of the force in correspondence to the distance of the affected object
  75771. */
  75772. var PhysicsRadialImpulseFalloff;
  75773. (function (PhysicsRadialImpulseFalloff) {
  75774. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75775. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75776. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75777. /**
  75778. * The strenght of the force in correspondence to the distance of the affected object
  75779. */
  75780. var PhysicsUpdraftMode;
  75781. (function (PhysicsUpdraftMode) {
  75782. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75783. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75784. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75785. })(BABYLON || (BABYLON = {}));
  75786. //# sourceMappingURL=babylon.physicsHelper.js.map
  75787. var BABYLON;
  75788. (function (BABYLON) {
  75789. var CannonJSPlugin = /** @class */ (function () {
  75790. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75791. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75792. if (iterations === void 0) { iterations = 10; }
  75793. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75794. this.name = "CannonJSPlugin";
  75795. this._physicsMaterials = new Array();
  75796. this._fixedTimeStep = 1 / 60;
  75797. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75798. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75799. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75800. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75801. this._tmpPosition = BABYLON.Vector3.Zero();
  75802. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75803. this._tmpUnityRotation = new BABYLON.Quaternion();
  75804. if (!this.isSupported()) {
  75805. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75806. return;
  75807. }
  75808. this._extendNamespace();
  75809. this.world = new this.BJSCANNON.World();
  75810. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75811. this.world.solver.iterations = iterations;
  75812. }
  75813. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75814. this.world.gravity.copy(gravity);
  75815. };
  75816. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75817. this._fixedTimeStep = timeStep;
  75818. };
  75819. CannonJSPlugin.prototype.getTimeStep = function () {
  75820. return this._fixedTimeStep;
  75821. };
  75822. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75823. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75824. };
  75825. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75826. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75827. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75828. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75829. };
  75830. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75831. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75832. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75833. impostor.physicsBody.applyForce(impulse, worldPoint);
  75834. };
  75835. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75836. //parent-child relationship. Does this impostor has a parent impostor?
  75837. if (impostor.parent) {
  75838. if (impostor.physicsBody) {
  75839. this.removePhysicsBody(impostor);
  75840. //TODO is that needed?
  75841. impostor.forceUpdate();
  75842. }
  75843. return;
  75844. }
  75845. //should a new body be created for this impostor?
  75846. if (impostor.isBodyInitRequired()) {
  75847. var shape = this._createShape(impostor);
  75848. //unregister events, if body is being changed
  75849. var oldBody = impostor.physicsBody;
  75850. if (oldBody) {
  75851. this.removePhysicsBody(impostor);
  75852. }
  75853. //create the body and material
  75854. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75855. var bodyCreationObject = {
  75856. mass: impostor.getParam("mass"),
  75857. material: material
  75858. };
  75859. // A simple extend, in case native options were used.
  75860. var nativeOptions = impostor.getParam("nativeOptions");
  75861. for (var key in nativeOptions) {
  75862. if (nativeOptions.hasOwnProperty(key)) {
  75863. bodyCreationObject[key] = nativeOptions[key];
  75864. }
  75865. }
  75866. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75867. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75868. this.world.addEventListener("preStep", impostor.beforeStep);
  75869. this.world.addEventListener("postStep", impostor.afterStep);
  75870. impostor.physicsBody.addShape(shape);
  75871. this.world.add(impostor.physicsBody);
  75872. //try to keep the body moving in the right direction by taking old properties.
  75873. //Should be tested!
  75874. if (oldBody) {
  75875. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75876. impostor.physicsBody[param].copy(oldBody[param]);
  75877. });
  75878. }
  75879. this._processChildMeshes(impostor);
  75880. }
  75881. //now update the body's transformation
  75882. this._updatePhysicsBodyTransformation(impostor);
  75883. };
  75884. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75885. var _this = this;
  75886. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75887. var currentRotation = mainImpostor.object.rotationQuaternion;
  75888. if (meshChildren.length) {
  75889. var processMesh = function (localPosition, mesh) {
  75890. if (!currentRotation || !mesh.rotationQuaternion) {
  75891. return;
  75892. }
  75893. var childImpostor = mesh.getPhysicsImpostor();
  75894. if (childImpostor) {
  75895. var parent = childImpostor.parent;
  75896. if (parent !== mainImpostor) {
  75897. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75898. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75899. if (childImpostor.physicsBody) {
  75900. _this.removePhysicsBody(childImpostor);
  75901. childImpostor.physicsBody = null;
  75902. }
  75903. childImpostor.parent = mainImpostor;
  75904. childImpostor.resetUpdateFlags();
  75905. 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));
  75906. //Add the mass of the children.
  75907. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75908. }
  75909. }
  75910. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75911. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75912. };
  75913. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75914. }
  75915. };
  75916. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75917. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75918. this.world.removeEventListener("preStep", impostor.beforeStep);
  75919. this.world.removeEventListener("postStep", impostor.afterStep);
  75920. this.world.remove(impostor.physicsBody);
  75921. };
  75922. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75923. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75924. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75925. if (!mainBody || !connectedBody) {
  75926. return;
  75927. }
  75928. var constraint;
  75929. var jointData = impostorJoint.joint.jointData;
  75930. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75931. var constraintData = {
  75932. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75933. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75934. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75935. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75936. maxForce: jointData.nativeParams.maxForce,
  75937. collideConnected: !!jointData.collision
  75938. };
  75939. switch (impostorJoint.joint.type) {
  75940. case BABYLON.PhysicsJoint.HingeJoint:
  75941. case BABYLON.PhysicsJoint.Hinge2Joint:
  75942. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  75943. break;
  75944. case BABYLON.PhysicsJoint.DistanceJoint:
  75945. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  75946. break;
  75947. case BABYLON.PhysicsJoint.SpringJoint:
  75948. var springData = jointData;
  75949. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  75950. restLength: springData.length,
  75951. stiffness: springData.stiffness,
  75952. damping: springData.damping,
  75953. localAnchorA: constraintData.pivotA,
  75954. localAnchorB: constraintData.pivotB
  75955. });
  75956. break;
  75957. case BABYLON.PhysicsJoint.LockJoint:
  75958. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  75959. break;
  75960. case BABYLON.PhysicsJoint.PointToPointJoint:
  75961. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75962. default:
  75963. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  75964. break;
  75965. }
  75966. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  75967. constraint.collideConnected = !!jointData.collision;
  75968. impostorJoint.joint.physicsJoint = constraint;
  75969. //don't add spring as constraint, as it is not one.
  75970. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  75971. this.world.addConstraint(constraint);
  75972. }
  75973. else {
  75974. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  75975. constraint.applyForce();
  75976. });
  75977. }
  75978. };
  75979. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75980. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  75981. };
  75982. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  75983. var index;
  75984. var mat;
  75985. for (index = 0; index < this._physicsMaterials.length; index++) {
  75986. mat = this._physicsMaterials[index];
  75987. if (mat.friction === friction && mat.restitution === restitution) {
  75988. return mat;
  75989. }
  75990. }
  75991. var currentMat = new this.BJSCANNON.Material(name);
  75992. currentMat.friction = friction;
  75993. currentMat.restitution = restitution;
  75994. this._physicsMaterials.push(currentMat);
  75995. return currentMat;
  75996. };
  75997. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  75998. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  75999. };
  76000. CannonJSPlugin.prototype._createShape = function (impostor) {
  76001. var object = impostor.object;
  76002. var returnValue;
  76003. var extendSize = impostor.getObjectExtendSize();
  76004. switch (impostor.type) {
  76005. case BABYLON.PhysicsImpostor.SphereImpostor:
  76006. var radiusX = extendSize.x;
  76007. var radiusY = extendSize.y;
  76008. var radiusZ = extendSize.z;
  76009. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76010. break;
  76011. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76012. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76013. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76014. break;
  76015. case BABYLON.PhysicsImpostor.BoxImpostor:
  76016. var box = extendSize.scale(0.5);
  76017. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76018. break;
  76019. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76020. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76021. returnValue = new this.BJSCANNON.Plane();
  76022. break;
  76023. case BABYLON.PhysicsImpostor.MeshImpostor:
  76024. // should transform the vertex data to world coordinates!!
  76025. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76026. var rawFaces = object.getIndices ? object.getIndices() : [];
  76027. if (!rawVerts)
  76028. return;
  76029. // get only scale! so the object could transform correctly.
  76030. var oldPosition = object.position.clone();
  76031. var oldRotation = object.rotation && object.rotation.clone();
  76032. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76033. object.position.copyFromFloats(0, 0, 0);
  76034. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76035. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76036. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76037. var transform = object.computeWorldMatrix(true);
  76038. // convert rawVerts to object space
  76039. var temp = new Array();
  76040. var index;
  76041. for (index = 0; index < rawVerts.length; index += 3) {
  76042. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76043. }
  76044. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76045. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76046. //now set back the transformation!
  76047. object.position.copyFrom(oldPosition);
  76048. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76049. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76050. break;
  76051. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76052. var oldPosition2 = object.position.clone();
  76053. var oldRotation2 = object.rotation && object.rotation.clone();
  76054. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76055. object.position.copyFromFloats(0, 0, 0);
  76056. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76057. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76058. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76059. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76060. returnValue = this._createHeightmap(object);
  76061. object.position.copyFrom(oldPosition2);
  76062. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76063. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76064. object.computeWorldMatrix(true);
  76065. break;
  76066. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76067. returnValue = new this.BJSCANNON.Particle();
  76068. break;
  76069. }
  76070. return returnValue;
  76071. };
  76072. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76073. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76074. var transform = object.computeWorldMatrix(true);
  76075. // convert rawVerts to object space
  76076. var temp = new Array();
  76077. var index;
  76078. for (index = 0; index < pos.length; index += 3) {
  76079. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76080. }
  76081. pos = temp;
  76082. var matrix = new Array();
  76083. //For now pointDepth will not be used and will be automatically calculated.
  76084. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76085. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76086. var boundingInfo = object.getBoundingInfo();
  76087. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76088. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76089. var elementSize = dim * 2 / arraySize;
  76090. for (var i = 0; i < pos.length; i = i + 3) {
  76091. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76092. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76093. var y = -pos[i + 2] + minY;
  76094. if (!matrix[x]) {
  76095. matrix[x] = [];
  76096. }
  76097. if (!matrix[x][z]) {
  76098. matrix[x][z] = y;
  76099. }
  76100. matrix[x][z] = Math.max(y, matrix[x][z]);
  76101. }
  76102. for (var x = 0; x <= arraySize; ++x) {
  76103. if (!matrix[x]) {
  76104. var loc = 1;
  76105. while (!matrix[(x + loc) % arraySize]) {
  76106. loc++;
  76107. }
  76108. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76109. //console.log("missing x", x);
  76110. }
  76111. for (var z = 0; z <= arraySize; ++z) {
  76112. if (!matrix[x][z]) {
  76113. var loc = 1;
  76114. var newValue;
  76115. while (newValue === undefined) {
  76116. newValue = matrix[x][(z + loc++) % arraySize];
  76117. }
  76118. matrix[x][z] = newValue;
  76119. }
  76120. }
  76121. }
  76122. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76123. elementSize: elementSize
  76124. });
  76125. //For future reference, needed for body transformation
  76126. shape.minY = minY;
  76127. return shape;
  76128. };
  76129. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76130. var object = impostor.object;
  76131. //make sure it is updated...
  76132. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76133. // The delta between the mesh position and the mesh bounding box center
  76134. var bInfo = object.getBoundingInfo();
  76135. if (!bInfo)
  76136. return;
  76137. var center = impostor.getObjectCenter();
  76138. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76139. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76140. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76141. this._tmpPosition.copyFrom(center);
  76142. var quaternion = object.rotationQuaternion;
  76143. if (!quaternion) {
  76144. return;
  76145. }
  76146. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76147. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76148. //-90 DEG in X, precalculated
  76149. quaternion = quaternion.multiply(this._minus90X);
  76150. //Invert! (Precalculated, 90 deg in X)
  76151. //No need to clone. this will never change.
  76152. impostor.setDeltaRotation(this._plus90X);
  76153. }
  76154. //If it is a heightfield, if should be centered.
  76155. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76156. var mesh = object;
  76157. var boundingInfo = mesh.getBoundingInfo();
  76158. //calculate the correct body position:
  76159. var rotationQuaternion = mesh.rotationQuaternion;
  76160. mesh.rotationQuaternion = this._tmpUnityRotation;
  76161. mesh.computeWorldMatrix(true);
  76162. //get original center with no rotation
  76163. var c = center.clone();
  76164. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76165. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76166. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76167. mesh.setPreTransformMatrix(p);
  76168. mesh.computeWorldMatrix(true);
  76169. //calculate the translation
  76170. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76171. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76172. //add it inverted to the delta
  76173. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76174. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76175. //rotation is back
  76176. mesh.rotationQuaternion = rotationQuaternion;
  76177. mesh.setPreTransformMatrix(oldPivot);
  76178. mesh.computeWorldMatrix(true);
  76179. }
  76180. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76181. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76182. //this._tmpPosition.copyFrom(object.position);
  76183. }
  76184. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76185. //Now update the impostor object
  76186. impostor.physicsBody.position.copy(this._tmpPosition);
  76187. impostor.physicsBody.quaternion.copy(quaternion);
  76188. };
  76189. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76190. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76191. if (impostor.object.rotationQuaternion) {
  76192. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76193. }
  76194. };
  76195. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76196. impostor.physicsBody.position.copy(newPosition);
  76197. impostor.physicsBody.quaternion.copy(newRotation);
  76198. };
  76199. CannonJSPlugin.prototype.isSupported = function () {
  76200. return this.BJSCANNON !== undefined;
  76201. };
  76202. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76203. impostor.physicsBody.velocity.copy(velocity);
  76204. };
  76205. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76206. impostor.physicsBody.angularVelocity.copy(velocity);
  76207. };
  76208. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76209. var v = impostor.physicsBody.velocity;
  76210. if (!v) {
  76211. return null;
  76212. }
  76213. return new BABYLON.Vector3(v.x, v.y, v.z);
  76214. };
  76215. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76216. var v = impostor.physicsBody.angularVelocity;
  76217. if (!v) {
  76218. return null;
  76219. }
  76220. return new BABYLON.Vector3(v.x, v.y, v.z);
  76221. };
  76222. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76223. impostor.physicsBody.mass = mass;
  76224. impostor.physicsBody.updateMassProperties();
  76225. };
  76226. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76227. return impostor.physicsBody.mass;
  76228. };
  76229. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76230. return impostor.physicsBody.material.friction;
  76231. };
  76232. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76233. impostor.physicsBody.material.friction = friction;
  76234. };
  76235. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76236. return impostor.physicsBody.material.restitution;
  76237. };
  76238. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76239. impostor.physicsBody.material.restitution = restitution;
  76240. };
  76241. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76242. impostor.physicsBody.sleep();
  76243. };
  76244. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76245. impostor.physicsBody.wakeUp();
  76246. };
  76247. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76248. joint.physicsJoint.distance = maxDistance;
  76249. };
  76250. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76251. // if (!motorIndex) {
  76252. // joint.physicsJoint.enableMotor();
  76253. // }
  76254. // }
  76255. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76256. // if (!motorIndex) {
  76257. // joint.physicsJoint.disableMotor();
  76258. // }
  76259. // }
  76260. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76261. if (!motorIndex) {
  76262. joint.physicsJoint.enableMotor();
  76263. joint.physicsJoint.setMotorSpeed(speed);
  76264. if (maxForce) {
  76265. this.setLimit(joint, maxForce);
  76266. }
  76267. }
  76268. };
  76269. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76270. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76271. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76272. };
  76273. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76274. var body = impostor.physicsBody;
  76275. mesh.position.x = body.position.x;
  76276. mesh.position.y = body.position.y;
  76277. mesh.position.z = body.position.z;
  76278. if (mesh.rotationQuaternion) {
  76279. mesh.rotationQuaternion.x = body.quaternion.x;
  76280. mesh.rotationQuaternion.y = body.quaternion.y;
  76281. mesh.rotationQuaternion.z = body.quaternion.z;
  76282. mesh.rotationQuaternion.w = body.quaternion.w;
  76283. }
  76284. };
  76285. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76286. var shape = impostor.physicsBody.shapes[0];
  76287. return shape.boundingSphereRadius;
  76288. };
  76289. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76290. var shape = impostor.physicsBody.shapes[0];
  76291. result.x = shape.halfExtents.x * 2;
  76292. result.y = shape.halfExtents.y * 2;
  76293. result.z = shape.halfExtents.z * 2;
  76294. };
  76295. CannonJSPlugin.prototype.dispose = function () {
  76296. };
  76297. CannonJSPlugin.prototype._extendNamespace = function () {
  76298. //this will force cannon to execute at least one step when using interpolation
  76299. var step_tmp1 = new this.BJSCANNON.Vec3();
  76300. var Engine = this.BJSCANNON;
  76301. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76302. maxSubSteps = maxSubSteps || 10;
  76303. timeSinceLastCalled = timeSinceLastCalled || 0;
  76304. if (timeSinceLastCalled === 0) {
  76305. this.internalStep(dt);
  76306. this.time += dt;
  76307. }
  76308. else {
  76309. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76310. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76311. var t0 = performance.now();
  76312. for (var i = 0; i !== internalSteps; i++) {
  76313. this.internalStep(dt);
  76314. if (performance.now() - t0 > dt * 1000) {
  76315. break;
  76316. }
  76317. }
  76318. this.time += timeSinceLastCalled;
  76319. var h = this.time % dt;
  76320. var h_div_dt = h / dt;
  76321. var interpvelo = step_tmp1;
  76322. var bodies = this.bodies;
  76323. for (var j = 0; j !== bodies.length; j++) {
  76324. var b = bodies[j];
  76325. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76326. b.position.vsub(b.previousPosition, interpvelo);
  76327. interpvelo.scale(h_div_dt, interpvelo);
  76328. b.position.vadd(interpvelo, b.interpolatedPosition);
  76329. }
  76330. else {
  76331. b.interpolatedPosition.copy(b.position);
  76332. b.interpolatedQuaternion.copy(b.quaternion);
  76333. }
  76334. }
  76335. }
  76336. };
  76337. };
  76338. return CannonJSPlugin;
  76339. }());
  76340. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76341. })(BABYLON || (BABYLON = {}));
  76342. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76343. var BABYLON;
  76344. (function (BABYLON) {
  76345. var OimoJSPlugin = /** @class */ (function () {
  76346. function OimoJSPlugin(iterations) {
  76347. this.name = "OimoJSPlugin";
  76348. this._tmpImpostorsArray = [];
  76349. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76350. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76351. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76352. this.world.worldscale(1);
  76353. this.world.clear();
  76354. //making sure no stats are calculated
  76355. this.world.isNoStat = true;
  76356. }
  76357. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76358. this.world.gravity.copy(gravity);
  76359. };
  76360. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76361. this.world.timeStep = timeStep;
  76362. };
  76363. OimoJSPlugin.prototype.getTimeStep = function () {
  76364. return this.world.timeStep;
  76365. };
  76366. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76367. var _this = this;
  76368. impostors.forEach(function (impostor) {
  76369. impostor.beforeStep();
  76370. });
  76371. this.world.step();
  76372. impostors.forEach(function (impostor) {
  76373. impostor.afterStep();
  76374. //update the ordered impostors array
  76375. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76376. });
  76377. //check for collisions
  76378. var contact = this.world.contacts;
  76379. while (contact !== null) {
  76380. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76381. contact = contact.next;
  76382. continue;
  76383. }
  76384. //is this body colliding with any other? get the impostor
  76385. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76386. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76387. if (!mainImpostor || !collidingImpostor) {
  76388. contact = contact.next;
  76389. continue;
  76390. }
  76391. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76392. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76393. contact = contact.next;
  76394. }
  76395. };
  76396. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76397. var mass = impostor.physicsBody.massInfo.mass;
  76398. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76399. };
  76400. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76401. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76402. this.applyImpulse(impostor, force, contactPoint);
  76403. };
  76404. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76405. var _this = this;
  76406. //parent-child relationship. Does this impostor has a parent impostor?
  76407. if (impostor.parent) {
  76408. if (impostor.physicsBody) {
  76409. this.removePhysicsBody(impostor);
  76410. //TODO is that needed?
  76411. impostor.forceUpdate();
  76412. }
  76413. return;
  76414. }
  76415. if (impostor.isBodyInitRequired()) {
  76416. var bodyConfig = {
  76417. name: impostor.uniqueId,
  76418. //Oimo must have mass, also for static objects.
  76419. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76420. size: [],
  76421. type: [],
  76422. pos: [],
  76423. rot: [],
  76424. move: impostor.getParam("mass") !== 0,
  76425. //Supporting older versions of Oimo
  76426. world: this.world
  76427. };
  76428. var impostors = [impostor];
  76429. var addToArray = function (parent) {
  76430. if (!parent.getChildMeshes)
  76431. return;
  76432. parent.getChildMeshes().forEach(function (m) {
  76433. if (m.physicsImpostor) {
  76434. impostors.push(m.physicsImpostor);
  76435. //m.physicsImpostor._init();
  76436. }
  76437. });
  76438. };
  76439. addToArray(impostor.object);
  76440. var checkWithEpsilon_1 = function (value) {
  76441. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76442. };
  76443. impostors.forEach(function (i) {
  76444. if (!impostor.object.rotationQuaternion) {
  76445. return;
  76446. }
  76447. //get the correct bounding box
  76448. var oldQuaternion = i.object.rotationQuaternion;
  76449. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76450. x: impostor.object.rotationQuaternion.x,
  76451. y: impostor.object.rotationQuaternion.y,
  76452. z: impostor.object.rotationQuaternion.z,
  76453. s: impostor.object.rotationQuaternion.w
  76454. });
  76455. var extendSize = i.getObjectExtendSize();
  76456. if (i === impostor) {
  76457. var center = impostor.getObjectCenter();
  76458. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76459. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76460. //Can also use Array.prototype.push.apply
  76461. bodyConfig.pos.push(center.x);
  76462. bodyConfig.pos.push(center.y);
  76463. bodyConfig.pos.push(center.z);
  76464. //tmp solution
  76465. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76466. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76467. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76468. }
  76469. else {
  76470. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76471. bodyConfig.pos.push(localPosition.x);
  76472. bodyConfig.pos.push(localPosition.y);
  76473. bodyConfig.pos.push(localPosition.z);
  76474. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76475. bodyConfig.rot.push(0);
  76476. bodyConfig.rot.push(0);
  76477. bodyConfig.rot.push(0);
  76478. }
  76479. // register mesh
  76480. switch (i.type) {
  76481. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76482. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76483. case BABYLON.PhysicsImpostor.SphereImpostor:
  76484. var radiusX = extendSize.x;
  76485. var radiusY = extendSize.y;
  76486. var radiusZ = extendSize.z;
  76487. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76488. bodyConfig.type.push('sphere');
  76489. //due to the way oimo works with compounds, add 3 times
  76490. bodyConfig.size.push(size);
  76491. bodyConfig.size.push(size);
  76492. bodyConfig.size.push(size);
  76493. break;
  76494. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76495. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76496. var sizeY = checkWithEpsilon_1(extendSize.y);
  76497. bodyConfig.type.push('cylinder');
  76498. bodyConfig.size.push(sizeX);
  76499. bodyConfig.size.push(sizeY);
  76500. //due to the way oimo works with compounds, add one more value.
  76501. bodyConfig.size.push(sizeY);
  76502. break;
  76503. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76504. case BABYLON.PhysicsImpostor.BoxImpostor:
  76505. default:
  76506. var sizeX = checkWithEpsilon_1(extendSize.x);
  76507. var sizeY = checkWithEpsilon_1(extendSize.y);
  76508. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76509. bodyConfig.type.push('box');
  76510. bodyConfig.size.push(sizeX);
  76511. bodyConfig.size.push(sizeY);
  76512. bodyConfig.size.push(sizeZ);
  76513. break;
  76514. }
  76515. //actually not needed, but hey...
  76516. i.object.rotationQuaternion = oldQuaternion;
  76517. });
  76518. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76519. }
  76520. else {
  76521. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76522. }
  76523. impostor.setDeltaPosition(this._tmpPositionVector);
  76524. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76525. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76526. };
  76527. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76528. //impostor.physicsBody.dispose();
  76529. //Same as : (older oimo versions)
  76530. this.world.removeRigidBody(impostor.physicsBody);
  76531. };
  76532. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76533. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76534. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76535. if (!mainBody || !connectedBody) {
  76536. return;
  76537. }
  76538. var jointData = impostorJoint.joint.jointData;
  76539. var options = jointData.nativeParams || {};
  76540. var type;
  76541. var nativeJointData = {
  76542. body1: mainBody,
  76543. body2: connectedBody,
  76544. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76545. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76546. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76547. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76548. min: options.min,
  76549. max: options.max,
  76550. collision: options.collision || jointData.collision,
  76551. spring: options.spring,
  76552. //supporting older version of Oimo
  76553. world: this.world
  76554. };
  76555. switch (impostorJoint.joint.type) {
  76556. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76557. type = "jointBall";
  76558. break;
  76559. case BABYLON.PhysicsJoint.SpringJoint:
  76560. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76561. var springData = jointData;
  76562. nativeJointData.min = springData.length || nativeJointData.min;
  76563. //Max should also be set, just make sure it is at least min
  76564. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76565. case BABYLON.PhysicsJoint.DistanceJoint:
  76566. type = "jointDistance";
  76567. nativeJointData.max = jointData.maxDistance;
  76568. break;
  76569. case BABYLON.PhysicsJoint.PrismaticJoint:
  76570. type = "jointPrisme";
  76571. break;
  76572. case BABYLON.PhysicsJoint.SliderJoint:
  76573. type = "jointSlide";
  76574. break;
  76575. case BABYLON.PhysicsJoint.WheelJoint:
  76576. type = "jointWheel";
  76577. break;
  76578. case BABYLON.PhysicsJoint.HingeJoint:
  76579. default:
  76580. type = "jointHinge";
  76581. break;
  76582. }
  76583. nativeJointData.type = type;
  76584. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76585. };
  76586. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76587. //Bug in Oimo prevents us from disposing a joint in the playground
  76588. //joint.joint.physicsJoint.dispose();
  76589. //So we will bruteforce it!
  76590. try {
  76591. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76592. }
  76593. catch (e) {
  76594. BABYLON.Tools.Warn(e);
  76595. }
  76596. };
  76597. OimoJSPlugin.prototype.isSupported = function () {
  76598. return this.BJSOIMO !== undefined;
  76599. };
  76600. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76601. if (!impostor.physicsBody.sleeping) {
  76602. //TODO check that
  76603. if (impostor.physicsBody.shapes.next) {
  76604. var parentShape = this._getLastShape(impostor.physicsBody);
  76605. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76606. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76607. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76608. }
  76609. else {
  76610. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76611. }
  76612. if (impostor.object.rotationQuaternion) {
  76613. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76614. impostor.object.rotationQuaternion.normalize();
  76615. }
  76616. }
  76617. };
  76618. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76619. var body = impostor.physicsBody;
  76620. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76621. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76622. body.syncShapes();
  76623. body.awake();
  76624. };
  76625. OimoJSPlugin.prototype._getLastShape = function (body) {
  76626. var lastShape = body.shapes;
  76627. while (lastShape.next) {
  76628. lastShape = lastShape.next;
  76629. }
  76630. return lastShape;
  76631. };
  76632. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76633. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76634. };
  76635. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76636. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76637. };
  76638. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76639. var v = impostor.physicsBody.linearVelocity;
  76640. if (!v) {
  76641. return null;
  76642. }
  76643. return new BABYLON.Vector3(v.x, v.y, v.z);
  76644. };
  76645. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76646. var v = impostor.physicsBody.angularVelocity;
  76647. if (!v) {
  76648. return null;
  76649. }
  76650. return new BABYLON.Vector3(v.x, v.y, v.z);
  76651. };
  76652. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76653. var staticBody = mass === 0;
  76654. //this will actually set the body's density and not its mass.
  76655. //But this is how oimo treats the mass variable.
  76656. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76657. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76658. };
  76659. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76660. return impostor.physicsBody.shapes.density;
  76661. };
  76662. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76663. return impostor.physicsBody.shapes.friction;
  76664. };
  76665. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76666. impostor.physicsBody.shapes.friction = friction;
  76667. };
  76668. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76669. return impostor.physicsBody.shapes.restitution;
  76670. };
  76671. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76672. impostor.physicsBody.shapes.restitution = restitution;
  76673. };
  76674. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76675. impostor.physicsBody.sleep();
  76676. };
  76677. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76678. impostor.physicsBody.awake();
  76679. };
  76680. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76681. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76682. if (minDistance !== void 0) {
  76683. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76684. }
  76685. };
  76686. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76687. //TODO separate rotational and transational motors.
  76688. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76689. if (motor) {
  76690. motor.setMotor(speed, maxForce);
  76691. }
  76692. };
  76693. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76694. //TODO separate rotational and transational motors.
  76695. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76696. if (motor) {
  76697. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76698. }
  76699. };
  76700. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76701. var body = impostor.physicsBody;
  76702. mesh.position.x = body.position.x;
  76703. mesh.position.y = body.position.y;
  76704. mesh.position.z = body.position.z;
  76705. if (mesh.rotationQuaternion) {
  76706. mesh.rotationQuaternion.x = body.orientation.x;
  76707. mesh.rotationQuaternion.y = body.orientation.y;
  76708. mesh.rotationQuaternion.z = body.orientation.z;
  76709. mesh.rotationQuaternion.w = body.orientation.s;
  76710. }
  76711. };
  76712. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76713. return impostor.physicsBody.shapes.radius;
  76714. };
  76715. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76716. var shape = impostor.physicsBody.shapes;
  76717. result.x = shape.halfWidth * 2;
  76718. result.y = shape.halfHeight * 2;
  76719. result.z = shape.halfDepth * 2;
  76720. };
  76721. OimoJSPlugin.prototype.dispose = function () {
  76722. this.world.clear();
  76723. };
  76724. return OimoJSPlugin;
  76725. }());
  76726. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76727. })(BABYLON || (BABYLON = {}));
  76728. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76729. var BABYLON;
  76730. (function (BABYLON) {
  76731. /*
  76732. * Based on jsTGALoader - Javascript loader for TGA file
  76733. * By Vincent Thibault
  76734. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76735. */
  76736. var TGATools = /** @class */ (function () {
  76737. function TGATools() {
  76738. }
  76739. TGATools.GetTGAHeader = function (data) {
  76740. var offset = 0;
  76741. var header = {
  76742. id_length: data[offset++],
  76743. colormap_type: data[offset++],
  76744. image_type: data[offset++],
  76745. colormap_index: data[offset++] | data[offset++] << 8,
  76746. colormap_length: data[offset++] | data[offset++] << 8,
  76747. colormap_size: data[offset++],
  76748. origin: [
  76749. data[offset++] | data[offset++] << 8,
  76750. data[offset++] | data[offset++] << 8
  76751. ],
  76752. width: data[offset++] | data[offset++] << 8,
  76753. height: data[offset++] | data[offset++] << 8,
  76754. pixel_size: data[offset++],
  76755. flags: data[offset++]
  76756. };
  76757. return header;
  76758. };
  76759. TGATools.UploadContent = function (gl, data) {
  76760. // Not enough data to contain header ?
  76761. if (data.length < 19) {
  76762. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76763. return;
  76764. }
  76765. // Read Header
  76766. var offset = 18;
  76767. var header = TGATools.GetTGAHeader(data);
  76768. // Assume it's a valid Targa file.
  76769. if (header.id_length + offset > data.length) {
  76770. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76771. return;
  76772. }
  76773. // Skip not needed data
  76774. offset += header.id_length;
  76775. var use_rle = false;
  76776. var use_pal = false;
  76777. var use_grey = false;
  76778. // Get some informations.
  76779. switch (header.image_type) {
  76780. case TGATools._TYPE_RLE_INDEXED:
  76781. use_rle = true;
  76782. case TGATools._TYPE_INDEXED:
  76783. use_pal = true;
  76784. break;
  76785. case TGATools._TYPE_RLE_RGB:
  76786. use_rle = true;
  76787. case TGATools._TYPE_RGB:
  76788. // use_rgb = true;
  76789. break;
  76790. case TGATools._TYPE_RLE_GREY:
  76791. use_rle = true;
  76792. case TGATools._TYPE_GREY:
  76793. use_grey = true;
  76794. break;
  76795. }
  76796. var pixel_data;
  76797. // var numAlphaBits = header.flags & 0xf;
  76798. var pixel_size = header.pixel_size >> 3;
  76799. var pixel_total = header.width * header.height * pixel_size;
  76800. // Read palettes
  76801. var palettes;
  76802. if (use_pal) {
  76803. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76804. }
  76805. // Read LRE
  76806. if (use_rle) {
  76807. pixel_data = new Uint8Array(pixel_total);
  76808. var c, count, i;
  76809. var localOffset = 0;
  76810. var pixels = new Uint8Array(pixel_size);
  76811. while (offset < pixel_total && localOffset < pixel_total) {
  76812. c = data[offset++];
  76813. count = (c & 0x7f) + 1;
  76814. // RLE pixels
  76815. if (c & 0x80) {
  76816. // Bind pixel tmp array
  76817. for (i = 0; i < pixel_size; ++i) {
  76818. pixels[i] = data[offset++];
  76819. }
  76820. // Copy pixel array
  76821. for (i = 0; i < count; ++i) {
  76822. pixel_data.set(pixels, localOffset + i * pixel_size);
  76823. }
  76824. localOffset += pixel_size * count;
  76825. }
  76826. else {
  76827. count *= pixel_size;
  76828. for (i = 0; i < count; ++i) {
  76829. pixel_data[localOffset + i] = data[offset++];
  76830. }
  76831. localOffset += count;
  76832. }
  76833. }
  76834. }
  76835. else {
  76836. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76837. }
  76838. // Load to texture
  76839. var x_start, y_start, x_step, y_step, y_end, x_end;
  76840. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76841. default:
  76842. case TGATools._ORIGIN_UL:
  76843. x_start = 0;
  76844. x_step = 1;
  76845. x_end = header.width;
  76846. y_start = 0;
  76847. y_step = 1;
  76848. y_end = header.height;
  76849. break;
  76850. case TGATools._ORIGIN_BL:
  76851. x_start = 0;
  76852. x_step = 1;
  76853. x_end = header.width;
  76854. y_start = header.height - 1;
  76855. y_step = -1;
  76856. y_end = -1;
  76857. break;
  76858. case TGATools._ORIGIN_UR:
  76859. x_start = header.width - 1;
  76860. x_step = -1;
  76861. x_end = -1;
  76862. y_start = 0;
  76863. y_step = 1;
  76864. y_end = header.height;
  76865. break;
  76866. case TGATools._ORIGIN_BR:
  76867. x_start = header.width - 1;
  76868. x_step = -1;
  76869. x_end = -1;
  76870. y_start = header.height - 1;
  76871. y_step = -1;
  76872. y_end = -1;
  76873. break;
  76874. }
  76875. // Load the specify method
  76876. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76877. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76878. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76879. };
  76880. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76881. var image = pixel_data, colormap = palettes;
  76882. var width = header.width, height = header.height;
  76883. var color, i = 0, x, y;
  76884. var imageData = new Uint8Array(width * height * 4);
  76885. for (y = y_start; y !== y_end; y += y_step) {
  76886. for (x = x_start; x !== x_end; x += x_step, i++) {
  76887. color = image[i];
  76888. imageData[(x + width * y) * 4 + 3] = 255;
  76889. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76890. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76891. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76892. }
  76893. }
  76894. return imageData;
  76895. };
  76896. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76897. var image = pixel_data;
  76898. var width = header.width, height = header.height;
  76899. var color, i = 0, x, y;
  76900. var imageData = new Uint8Array(width * height * 4);
  76901. for (y = y_start; y !== y_end; y += y_step) {
  76902. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76903. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76904. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76905. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76906. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76907. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76908. }
  76909. }
  76910. return imageData;
  76911. };
  76912. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76913. var image = pixel_data;
  76914. var width = header.width, height = header.height;
  76915. var i = 0, x, y;
  76916. var imageData = new Uint8Array(width * height * 4);
  76917. for (y = y_start; y !== y_end; y += y_step) {
  76918. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76919. imageData[(x + width * y) * 4 + 3] = 255;
  76920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76923. }
  76924. }
  76925. return imageData;
  76926. };
  76927. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76928. var image = pixel_data;
  76929. var width = header.width, height = header.height;
  76930. var i = 0, x, y;
  76931. var imageData = new Uint8Array(width * height * 4);
  76932. for (y = y_start; y !== y_end; y += y_step) {
  76933. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76934. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76935. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76936. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76937. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76938. }
  76939. }
  76940. return imageData;
  76941. };
  76942. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76943. var image = pixel_data;
  76944. var width = header.width, height = header.height;
  76945. var color, i = 0, x, y;
  76946. var imageData = new Uint8Array(width * height * 4);
  76947. for (y = y_start; y !== y_end; y += y_step) {
  76948. for (x = x_start; x !== x_end; x += x_step, i++) {
  76949. color = image[i];
  76950. imageData[(x + width * y) * 4 + 0] = color;
  76951. imageData[(x + width * y) * 4 + 1] = color;
  76952. imageData[(x + width * y) * 4 + 2] = color;
  76953. imageData[(x + width * y) * 4 + 3] = 255;
  76954. }
  76955. }
  76956. return imageData;
  76957. };
  76958. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76959. var image = pixel_data;
  76960. var width = header.width, height = header.height;
  76961. var i = 0, x, y;
  76962. var imageData = new Uint8Array(width * height * 4);
  76963. for (y = y_start; y !== y_end; y += y_step) {
  76964. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76965. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  76966. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  76967. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76968. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  76969. }
  76970. }
  76971. return imageData;
  76972. };
  76973. //private static _TYPE_NO_DATA = 0;
  76974. TGATools._TYPE_INDEXED = 1;
  76975. TGATools._TYPE_RGB = 2;
  76976. TGATools._TYPE_GREY = 3;
  76977. TGATools._TYPE_RLE_INDEXED = 9;
  76978. TGATools._TYPE_RLE_RGB = 10;
  76979. TGATools._TYPE_RLE_GREY = 11;
  76980. TGATools._ORIGIN_MASK = 0x30;
  76981. TGATools._ORIGIN_SHIFT = 0x04;
  76982. TGATools._ORIGIN_BL = 0x00;
  76983. TGATools._ORIGIN_BR = 0x01;
  76984. TGATools._ORIGIN_UL = 0x02;
  76985. TGATools._ORIGIN_UR = 0x03;
  76986. return TGATools;
  76987. }());
  76988. BABYLON.TGATools = TGATools;
  76989. })(BABYLON || (BABYLON = {}));
  76990. //# sourceMappingURL=babylon.tga.js.map
  76991. var BABYLON;
  76992. (function (BABYLON) {
  76993. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  76994. // All values and structures referenced from:
  76995. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  76996. var DDS_MAGIC = 0x20534444;
  76997. var
  76998. //DDSD_CAPS = 0x1,
  76999. //DDSD_HEIGHT = 0x2,
  77000. //DDSD_WIDTH = 0x4,
  77001. //DDSD_PITCH = 0x8,
  77002. //DDSD_PIXELFORMAT = 0x1000,
  77003. DDSD_MIPMAPCOUNT = 0x20000;
  77004. //DDSD_LINEARSIZE = 0x80000,
  77005. //DDSD_DEPTH = 0x800000;
  77006. // var DDSCAPS_COMPLEX = 0x8,
  77007. // DDSCAPS_MIPMAP = 0x400000,
  77008. // DDSCAPS_TEXTURE = 0x1000;
  77009. var DDSCAPS2_CUBEMAP = 0x200;
  77010. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77011. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77012. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77013. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77014. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77015. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77016. // DDSCAPS2_VOLUME = 0x200000;
  77017. var
  77018. //DDPF_ALPHAPIXELS = 0x1,
  77019. //DDPF_ALPHA = 0x2,
  77020. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77021. //DDPF_YUV = 0x200,
  77022. DDPF_LUMINANCE = 0x20000;
  77023. function FourCCToInt32(value) {
  77024. return value.charCodeAt(0) +
  77025. (value.charCodeAt(1) << 8) +
  77026. (value.charCodeAt(2) << 16) +
  77027. (value.charCodeAt(3) << 24);
  77028. }
  77029. function Int32ToFourCC(value) {
  77030. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77031. }
  77032. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77033. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77034. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77035. var FOURCC_DX10 = FourCCToInt32("DX10");
  77036. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77037. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77038. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77039. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77040. var headerLengthInt = 31; // The header length in 32 bit ints
  77041. // Offsets into the header array
  77042. var off_magic = 0;
  77043. var off_size = 1;
  77044. var off_flags = 2;
  77045. var off_height = 3;
  77046. var off_width = 4;
  77047. var off_mipmapCount = 7;
  77048. var off_pfFlags = 20;
  77049. var off_pfFourCC = 21;
  77050. var off_RGBbpp = 22;
  77051. var off_RMask = 23;
  77052. var off_GMask = 24;
  77053. var off_BMask = 25;
  77054. var off_AMask = 26;
  77055. // var off_caps1 = 27;
  77056. var off_caps2 = 28;
  77057. // var off_caps3 = 29;
  77058. // var off_caps4 = 30;
  77059. var off_dxgiFormat = 32;
  77060. ;
  77061. var DDSTools = /** @class */ (function () {
  77062. function DDSTools() {
  77063. }
  77064. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77065. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77066. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77067. var mipmapCount = 1;
  77068. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77069. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77070. }
  77071. var fourCC = header[off_pfFourCC];
  77072. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77073. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77074. switch (fourCC) {
  77075. case FOURCC_D3DFMT_R16G16B16A16F:
  77076. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77077. break;
  77078. case FOURCC_D3DFMT_R32G32B32A32F:
  77079. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77080. break;
  77081. case FOURCC_DX10:
  77082. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77083. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77084. break;
  77085. }
  77086. }
  77087. return {
  77088. width: header[off_width],
  77089. height: header[off_height],
  77090. mipmapCount: mipmapCount,
  77091. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77092. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77093. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77094. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77095. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77096. dxgiFormat: dxgiFormat,
  77097. textureType: textureType
  77098. };
  77099. };
  77100. DDSTools._ToHalfFloat = function (value) {
  77101. if (!DDSTools._FloatView) {
  77102. DDSTools._FloatView = new Float32Array(1);
  77103. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77104. }
  77105. DDSTools._FloatView[0] = value;
  77106. var x = DDSTools._Int32View[0];
  77107. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77108. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77109. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77110. /* If zero, or denormal, or exponent underflows too much for a denormal
  77111. * half, return signed zero. */
  77112. if (e < 103) {
  77113. return bits;
  77114. }
  77115. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77116. if (e > 142) {
  77117. bits |= 0x7c00;
  77118. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77119. * not Inf, so make sure we set one mantissa bit too. */
  77120. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77121. return bits;
  77122. }
  77123. /* If exponent underflows but not too much, return a denormal */
  77124. if (e < 113) {
  77125. m |= 0x0800;
  77126. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77127. * to 1, which is OK. */
  77128. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77129. return bits;
  77130. }
  77131. bits |= ((e - 112) << 10) | (m >> 1);
  77132. bits += m & 1;
  77133. return bits;
  77134. };
  77135. DDSTools._FromHalfFloat = function (value) {
  77136. var s = (value & 0x8000) >> 15;
  77137. var e = (value & 0x7C00) >> 10;
  77138. var f = value & 0x03FF;
  77139. if (e === 0) {
  77140. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77141. }
  77142. else if (e == 0x1F) {
  77143. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77144. }
  77145. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77146. };
  77147. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77148. var destArray = new Float32Array(dataLength);
  77149. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77150. var index = 0;
  77151. for (var y = 0; y < height; y++) {
  77152. for (var x = 0; x < width; x++) {
  77153. var srcPos = (x + y * width) * 4;
  77154. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77155. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77156. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77157. if (DDSTools.StoreLODInAlphaChannel) {
  77158. destArray[index + 3] = lod;
  77159. }
  77160. else {
  77161. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77162. }
  77163. index += 4;
  77164. }
  77165. }
  77166. return destArray;
  77167. };
  77168. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77169. if (DDSTools.StoreLODInAlphaChannel) {
  77170. var destArray = new Uint16Array(dataLength);
  77171. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77172. var index = 0;
  77173. for (var y = 0; y < height; y++) {
  77174. for (var x = 0; x < width; x++) {
  77175. var srcPos = (x + y * width) * 4;
  77176. destArray[index] = srcData[srcPos];
  77177. destArray[index + 1] = srcData[srcPos + 1];
  77178. destArray[index + 2] = srcData[srcPos + 2];
  77179. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77180. index += 4;
  77181. }
  77182. }
  77183. return destArray;
  77184. }
  77185. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77186. };
  77187. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77188. if (DDSTools.StoreLODInAlphaChannel) {
  77189. var destArray = new Float32Array(dataLength);
  77190. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77191. var index = 0;
  77192. for (var y = 0; y < height; y++) {
  77193. for (var x = 0; x < width; x++) {
  77194. var srcPos = (x + y * width) * 4;
  77195. destArray[index] = srcData[srcPos];
  77196. destArray[index + 1] = srcData[srcPos + 1];
  77197. destArray[index + 2] = srcData[srcPos + 2];
  77198. destArray[index + 3] = lod;
  77199. index += 4;
  77200. }
  77201. }
  77202. return destArray;
  77203. }
  77204. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77205. };
  77206. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77207. var destArray = new Uint8Array(dataLength);
  77208. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77209. var index = 0;
  77210. for (var y = 0; y < height; y++) {
  77211. for (var x = 0; x < width; x++) {
  77212. var srcPos = (x + y * width) * 4;
  77213. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77214. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77215. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77216. if (DDSTools.StoreLODInAlphaChannel) {
  77217. destArray[index + 3] = lod;
  77218. }
  77219. else {
  77220. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77221. }
  77222. index += 4;
  77223. }
  77224. }
  77225. return destArray;
  77226. };
  77227. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77228. var destArray = new Uint8Array(dataLength);
  77229. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77230. var index = 0;
  77231. for (var y = 0; y < height; y++) {
  77232. for (var x = 0; x < width; x++) {
  77233. var srcPos = (x + y * width) * 4;
  77234. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77235. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77236. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77237. if (DDSTools.StoreLODInAlphaChannel) {
  77238. destArray[index + 3] = lod;
  77239. }
  77240. else {
  77241. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77242. }
  77243. index += 4;
  77244. }
  77245. }
  77246. return destArray;
  77247. };
  77248. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77249. var byteArray = new Uint8Array(dataLength);
  77250. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77251. var index = 0;
  77252. for (var y = 0; y < height; y++) {
  77253. for (var x = 0; x < width; x++) {
  77254. var srcPos = (x + y * width) * 4;
  77255. byteArray[index] = srcData[srcPos + rOffset];
  77256. byteArray[index + 1] = srcData[srcPos + gOffset];
  77257. byteArray[index + 2] = srcData[srcPos + bOffset];
  77258. byteArray[index + 3] = srcData[srcPos + aOffset];
  77259. index += 4;
  77260. }
  77261. }
  77262. return byteArray;
  77263. };
  77264. DDSTools._ExtractLongWordOrder = function (value) {
  77265. if (value === 0 || value === 255 || value === -16777216) {
  77266. return 0;
  77267. }
  77268. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77269. };
  77270. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77271. var byteArray = new Uint8Array(dataLength);
  77272. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77273. var index = 0;
  77274. for (var y = 0; y < height; y++) {
  77275. for (var x = 0; x < width; x++) {
  77276. var srcPos = (x + y * width) * 3;
  77277. byteArray[index] = srcData[srcPos + rOffset];
  77278. byteArray[index + 1] = srcData[srcPos + gOffset];
  77279. byteArray[index + 2] = srcData[srcPos + bOffset];
  77280. index += 3;
  77281. }
  77282. }
  77283. return byteArray;
  77284. };
  77285. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77286. var byteArray = new Uint8Array(dataLength);
  77287. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77288. var index = 0;
  77289. for (var y = 0; y < height; y++) {
  77290. for (var x = 0; x < width; x++) {
  77291. var srcPos = (x + y * width);
  77292. byteArray[index] = srcData[srcPos];
  77293. index++;
  77294. }
  77295. }
  77296. return byteArray;
  77297. };
  77298. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77299. if (lodIndex === void 0) { lodIndex = -1; }
  77300. var ext = engine.getCaps().s3tc;
  77301. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77302. var fourCC, width, height, dataLength = 0, dataOffset;
  77303. var byteArray, mipmapCount, mip;
  77304. var internalFormat = 0;
  77305. var format = 0;
  77306. var blockBytes = 1;
  77307. if (header[off_magic] !== DDS_MAGIC) {
  77308. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77309. return;
  77310. }
  77311. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77312. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77313. return;
  77314. }
  77315. if (info.isCompressed && !ext) {
  77316. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77317. return;
  77318. }
  77319. var bpp = header[off_RGBbpp];
  77320. dataOffset = header[off_size] + 4;
  77321. var computeFormats = false;
  77322. if (info.isFourCC) {
  77323. fourCC = header[off_pfFourCC];
  77324. switch (fourCC) {
  77325. case FOURCC_DXT1:
  77326. blockBytes = 8;
  77327. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77328. break;
  77329. case FOURCC_DXT3:
  77330. blockBytes = 16;
  77331. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77332. break;
  77333. case FOURCC_DXT5:
  77334. blockBytes = 16;
  77335. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77336. break;
  77337. case FOURCC_D3DFMT_R16G16B16A16F:
  77338. computeFormats = true;
  77339. break;
  77340. case FOURCC_D3DFMT_R32G32B32A32F:
  77341. computeFormats = true;
  77342. break;
  77343. case FOURCC_DX10:
  77344. // There is an additionnal header so dataOffset need to be changed
  77345. dataOffset += 5 * 4; // 5 uints
  77346. var supported = false;
  77347. switch (info.dxgiFormat) {
  77348. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77349. computeFormats = true;
  77350. supported = true;
  77351. break;
  77352. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77353. info.isRGB = true;
  77354. info.isFourCC = false;
  77355. bpp = 32;
  77356. supported = true;
  77357. break;
  77358. }
  77359. if (supported) {
  77360. break;
  77361. }
  77362. default:
  77363. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77364. return;
  77365. }
  77366. }
  77367. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77368. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77369. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77370. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77371. if (computeFormats) {
  77372. format = engine._getWebGLTextureType(info.textureType);
  77373. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77374. }
  77375. mipmapCount = 1;
  77376. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77377. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77378. }
  77379. for (var face = 0; face < faces; face++) {
  77380. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77381. width = header[off_width];
  77382. height = header[off_height];
  77383. for (mip = 0; mip < mipmapCount; ++mip) {
  77384. if (lodIndex === -1 || lodIndex === mip) {
  77385. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77386. var i = (lodIndex === -1) ? mip : 0;
  77387. if (!info.isCompressed && info.isFourCC) {
  77388. dataLength = width * height * 4;
  77389. var floatArray = null;
  77390. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77391. if (bpp === 128) {
  77392. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77393. }
  77394. else if (bpp === 64) {
  77395. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77396. }
  77397. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77398. format = engine._getWebGLTextureType(info.textureType);
  77399. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77400. }
  77401. else {
  77402. if (bpp === 128) {
  77403. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77404. }
  77405. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77406. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77407. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77408. format = engine._getWebGLTextureType(info.textureType);
  77409. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77410. }
  77411. else {
  77412. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77413. }
  77414. }
  77415. if (floatArray) {
  77416. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77417. }
  77418. }
  77419. else if (info.isRGB) {
  77420. if (bpp === 24) {
  77421. dataLength = width * height * 3;
  77422. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77423. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77424. }
  77425. else {
  77426. dataLength = width * height * 4;
  77427. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77428. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77429. }
  77430. }
  77431. else if (info.isLuminance) {
  77432. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77433. var unpaddedRowSize = width;
  77434. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77435. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77436. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77437. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77438. }
  77439. else {
  77440. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77441. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77442. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77443. }
  77444. }
  77445. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77446. width *= 0.5;
  77447. height *= 0.5;
  77448. width = Math.max(1.0, width);
  77449. height = Math.max(1.0, height);
  77450. }
  77451. if (currentFace !== undefined) {
  77452. // Loading a single face
  77453. break;
  77454. }
  77455. }
  77456. };
  77457. DDSTools.StoreLODInAlphaChannel = false;
  77458. return DDSTools;
  77459. }());
  77460. BABYLON.DDSTools = DDSTools;
  77461. })(BABYLON || (BABYLON = {}));
  77462. //# sourceMappingURL=babylon.dds.js.map
  77463. var BABYLON;
  77464. (function (BABYLON) {
  77465. /**
  77466. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77467. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77468. */
  77469. var KhronosTextureContainer = /** @class */ (function () {
  77470. /**
  77471. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77472. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77473. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77474. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77475. */
  77476. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77477. this.arrayBuffer = arrayBuffer;
  77478. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77479. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77480. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77481. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77482. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77483. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77484. BABYLON.Tools.Error("texture missing KTX identifier");
  77485. return;
  77486. }
  77487. // load the reset of the header in native 32 bit int
  77488. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77489. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77490. var oppositeEndianess = header[0] === 0x01020304;
  77491. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77492. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77493. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77494. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77495. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77496. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77497. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77498. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77499. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77500. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77501. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77502. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77503. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77504. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77505. if (this.glType !== 0) {
  77506. BABYLON.Tools.Error("only compressed formats currently supported");
  77507. return;
  77508. }
  77509. else {
  77510. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77511. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77512. }
  77513. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77514. BABYLON.Tools.Error("only 2D textures currently supported");
  77515. return;
  77516. }
  77517. if (this.numberOfArrayElements !== 0) {
  77518. BABYLON.Tools.Error("texture arrays not currently supported");
  77519. return;
  77520. }
  77521. if (this.numberOfFaces !== facesExpected) {
  77522. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77523. return;
  77524. }
  77525. // we now have a completely validated file, so could use existence of loadType as success
  77526. // would need to make this more elaborate & adjust checks above to support more than one load type
  77527. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77528. }
  77529. // not as fast hardware based, but will probably never need to use
  77530. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77531. return ((val & 0xFF) << 24)
  77532. | ((val & 0xFF00) << 8)
  77533. | ((val >> 8) & 0xFF00)
  77534. | ((val >> 24) & 0xFF);
  77535. };
  77536. /**
  77537. * It is assumed that the texture has already been created & is currently bound
  77538. */
  77539. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77540. switch (this.loadType) {
  77541. case KhronosTextureContainer.COMPRESSED_2D:
  77542. this._upload2DCompressedLevels(gl, loadMipmaps);
  77543. break;
  77544. case KhronosTextureContainer.TEX_2D:
  77545. case KhronosTextureContainer.COMPRESSED_3D:
  77546. case KhronosTextureContainer.TEX_3D:
  77547. }
  77548. };
  77549. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77550. // initialize width & height for level 1
  77551. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77552. var width = this.pixelWidth;
  77553. var height = this.pixelHeight;
  77554. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77555. for (var level = 0; level < mipmapCount; level++) {
  77556. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77557. for (var face = 0; face < this.numberOfFaces; face++) {
  77558. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77559. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77560. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77561. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77562. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77563. }
  77564. width = Math.max(1.0, width * 0.5);
  77565. height = Math.max(1.0, height * 0.5);
  77566. }
  77567. };
  77568. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77569. // load types
  77570. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77571. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77572. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77573. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77574. return KhronosTextureContainer;
  77575. }());
  77576. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77577. })(BABYLON || (BABYLON = {}));
  77578. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77579. var BABYLON;
  77580. (function (BABYLON) {
  77581. var Debug = /** @class */ (function () {
  77582. function Debug() {
  77583. }
  77584. Debug.AxesViewer = /** @class */ (function () {
  77585. function AxesViewer(scene, scaleLines) {
  77586. if (scaleLines === void 0) { scaleLines = 1; }
  77587. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77588. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77589. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77590. this.scaleLines = 1;
  77591. this.scaleLines = scaleLines;
  77592. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77593. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77594. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77595. this._xmesh.renderingGroupId = 2;
  77596. this._ymesh.renderingGroupId = 2;
  77597. this._zmesh.renderingGroupId = 2;
  77598. this._xmesh.material.checkReadyOnlyOnce = true;
  77599. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77600. this._ymesh.material.checkReadyOnlyOnce = true;
  77601. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77602. this._zmesh.material.checkReadyOnlyOnce = true;
  77603. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77604. this.scene = scene;
  77605. }
  77606. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77607. var scaleLines = this.scaleLines;
  77608. if (this._xmesh) {
  77609. this._xmesh.position.copyFrom(position);
  77610. }
  77611. if (this._ymesh) {
  77612. this._ymesh.position.copyFrom(position);
  77613. }
  77614. if (this._zmesh) {
  77615. this._zmesh.position.copyFrom(position);
  77616. }
  77617. var point2 = this._xline[1];
  77618. point2.x = xaxis.x * scaleLines;
  77619. point2.y = xaxis.y * scaleLines;
  77620. point2.z = xaxis.z * scaleLines;
  77621. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77622. point2 = this._yline[1];
  77623. point2.x = yaxis.x * scaleLines;
  77624. point2.y = yaxis.y * scaleLines;
  77625. point2.z = yaxis.z * scaleLines;
  77626. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77627. point2 = this._zline[1];
  77628. point2.x = zaxis.x * scaleLines;
  77629. point2.y = zaxis.y * scaleLines;
  77630. point2.z = zaxis.z * scaleLines;
  77631. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77632. };
  77633. AxesViewer.prototype.dispose = function () {
  77634. if (this._xmesh) {
  77635. this._xmesh.dispose();
  77636. }
  77637. if (this._ymesh) {
  77638. this._ymesh.dispose();
  77639. }
  77640. if (this._zmesh) {
  77641. this._zmesh.dispose();
  77642. }
  77643. this._xmesh = null;
  77644. this._ymesh = null;
  77645. this._zmesh = null;
  77646. this.scene = null;
  77647. };
  77648. return AxesViewer;
  77649. }());
  77650. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77651. __extends(BoneAxesViewer, _super);
  77652. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77653. if (scaleLines === void 0) { scaleLines = 1; }
  77654. var _this = _super.call(this, scene, scaleLines) || this;
  77655. _this.pos = BABYLON.Vector3.Zero();
  77656. _this.xaxis = BABYLON.Vector3.Zero();
  77657. _this.yaxis = BABYLON.Vector3.Zero();
  77658. _this.zaxis = BABYLON.Vector3.Zero();
  77659. _this.mesh = mesh;
  77660. _this.bone = bone;
  77661. return _this;
  77662. }
  77663. BoneAxesViewer.prototype.update = function () {
  77664. if (!this.mesh || !this.bone) {
  77665. return;
  77666. }
  77667. var bone = this.bone;
  77668. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77669. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77670. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77671. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77672. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77673. };
  77674. BoneAxesViewer.prototype.dispose = function () {
  77675. if (this.mesh) {
  77676. this.mesh = null;
  77677. this.bone = null;
  77678. _super.prototype.dispose.call(this);
  77679. }
  77680. };
  77681. return BoneAxesViewer;
  77682. }(Debug.AxesViewer));
  77683. Debug.PhysicsViewer = /** @class */ (function () {
  77684. function PhysicsViewer(scene) {
  77685. this._impostors = [];
  77686. this._meshes = [];
  77687. this._numMeshes = 0;
  77688. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77689. var physicEngine = this._scene.getPhysicsEngine();
  77690. if (physicEngine) {
  77691. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77692. }
  77693. }
  77694. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77695. var plugin = this._physicsEnginePlugin;
  77696. for (var i = 0; i < this._numMeshes; i++) {
  77697. var impostor = this._impostors[i];
  77698. if (!impostor) {
  77699. continue;
  77700. }
  77701. if (impostor.isDisposed) {
  77702. this.hideImpostor(this._impostors[i--]);
  77703. }
  77704. else {
  77705. var mesh = this._meshes[i];
  77706. if (mesh && plugin) {
  77707. plugin.syncMeshWithImpostor(mesh, impostor);
  77708. }
  77709. }
  77710. }
  77711. };
  77712. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77713. if (!this._scene) {
  77714. return;
  77715. }
  77716. for (var i = 0; i < this._numMeshes; i++) {
  77717. if (this._impostors[i] == impostor) {
  77718. return;
  77719. }
  77720. }
  77721. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77722. if (debugMesh) {
  77723. this._impostors[this._numMeshes] = impostor;
  77724. this._meshes[this._numMeshes] = debugMesh;
  77725. if (this._numMeshes === 0) {
  77726. this._renderFunction = this._updateDebugMeshes.bind(this);
  77727. this._scene.registerBeforeRender(this._renderFunction);
  77728. }
  77729. this._numMeshes++;
  77730. }
  77731. };
  77732. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77733. if (!impostor || !this._scene) {
  77734. return;
  77735. }
  77736. var removed = false;
  77737. for (var i = 0; i < this._numMeshes; i++) {
  77738. if (this._impostors[i] == impostor) {
  77739. var mesh = this._meshes[i];
  77740. if (!mesh) {
  77741. continue;
  77742. }
  77743. this._scene.removeMesh(mesh);
  77744. mesh.dispose();
  77745. this._numMeshes--;
  77746. if (this._numMeshes > 0) {
  77747. this._meshes[i] = this._meshes[this._numMeshes];
  77748. this._impostors[i] = this._impostors[this._numMeshes];
  77749. this._meshes[this._numMeshes] = null;
  77750. this._impostors[this._numMeshes] = null;
  77751. }
  77752. else {
  77753. this._meshes[0] = null;
  77754. this._impostors[0] = null;
  77755. }
  77756. removed = true;
  77757. break;
  77758. }
  77759. }
  77760. if (removed && this._numMeshes === 0) {
  77761. this._scene.unregisterBeforeRender(this._renderFunction);
  77762. }
  77763. };
  77764. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77765. if (!this._debugMaterial) {
  77766. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77767. this._debugMaterial.wireframe = true;
  77768. }
  77769. return this._debugMaterial;
  77770. };
  77771. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77772. if (!this._debugBoxMesh) {
  77773. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77774. this._debugBoxMesh.renderingGroupId = 1;
  77775. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77776. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77777. scene.removeMesh(this._debugBoxMesh);
  77778. }
  77779. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77780. };
  77781. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77782. if (!this._debugSphereMesh) {
  77783. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77784. this._debugSphereMesh.renderingGroupId = 1;
  77785. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77786. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77787. scene.removeMesh(this._debugSphereMesh);
  77788. }
  77789. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77790. };
  77791. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77792. var mesh = null;
  77793. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77794. mesh = this._getDebugBoxMesh(scene);
  77795. impostor.getBoxSizeToRef(mesh.scaling);
  77796. }
  77797. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77798. mesh = this._getDebugSphereMesh(scene);
  77799. var radius = impostor.getRadius();
  77800. mesh.scaling.x = radius * 2;
  77801. mesh.scaling.y = radius * 2;
  77802. mesh.scaling.z = radius * 2;
  77803. }
  77804. return mesh;
  77805. };
  77806. PhysicsViewer.prototype.dispose = function () {
  77807. for (var i = 0; i < this._numMeshes; i++) {
  77808. this.hideImpostor(this._impostors[i]);
  77809. }
  77810. if (this._debugBoxMesh) {
  77811. this._debugBoxMesh.dispose();
  77812. }
  77813. if (this._debugSphereMesh) {
  77814. this._debugSphereMesh.dispose();
  77815. }
  77816. if (this._debugMaterial) {
  77817. this._debugMaterial.dispose();
  77818. }
  77819. this._impostors.length = 0;
  77820. this._scene = null;
  77821. this._physicsEnginePlugin = null;
  77822. };
  77823. return PhysicsViewer;
  77824. }());
  77825. Debug.SkeletonViewer = /** @class */ (function () {
  77826. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77827. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77828. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77829. this.skeleton = skeleton;
  77830. this.mesh = mesh;
  77831. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77832. this.renderingGroupId = renderingGroupId;
  77833. this.color = BABYLON.Color3.White();
  77834. this._debugLines = new Array();
  77835. this._isEnabled = false;
  77836. this._scene = scene;
  77837. this.update();
  77838. this._renderFunction = this.update.bind(this);
  77839. }
  77840. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77841. get: function () {
  77842. return this._isEnabled;
  77843. },
  77844. set: function (value) {
  77845. if (this._isEnabled === value) {
  77846. return;
  77847. }
  77848. this._isEnabled = value;
  77849. if (value) {
  77850. this._scene.registerBeforeRender(this._renderFunction);
  77851. }
  77852. else {
  77853. this._scene.unregisterBeforeRender(this._renderFunction);
  77854. }
  77855. },
  77856. enumerable: true,
  77857. configurable: true
  77858. });
  77859. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77860. if (x === void 0) { x = 0; }
  77861. if (y === void 0) { y = 0; }
  77862. if (z === void 0) { z = 0; }
  77863. var tmat = BABYLON.Tmp.Matrix[0];
  77864. var parentBone = bone.getParent();
  77865. tmat.copyFrom(bone.getLocalMatrix());
  77866. if (x !== 0 || y !== 0 || z !== 0) {
  77867. var tmat2 = BABYLON.Tmp.Matrix[1];
  77868. BABYLON.Matrix.IdentityToRef(tmat2);
  77869. tmat2.m[12] = x;
  77870. tmat2.m[13] = y;
  77871. tmat2.m[14] = z;
  77872. tmat2.multiplyToRef(tmat, tmat);
  77873. }
  77874. if (parentBone) {
  77875. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77876. }
  77877. tmat.multiplyToRef(meshMat, tmat);
  77878. position.x = tmat.m[12];
  77879. position.y = tmat.m[13];
  77880. position.z = tmat.m[14];
  77881. };
  77882. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77883. var len = bones.length;
  77884. var meshPos = this.mesh.position;
  77885. for (var i = 0; i < len; i++) {
  77886. var bone = bones[i];
  77887. var points = this._debugLines[i];
  77888. if (!points) {
  77889. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77890. this._debugLines[i] = points;
  77891. }
  77892. this._getBonePosition(points[0], bone, meshMat);
  77893. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77894. points[0].subtractInPlace(meshPos);
  77895. points[1].subtractInPlace(meshPos);
  77896. }
  77897. };
  77898. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77899. var len = bones.length;
  77900. var boneNum = 0;
  77901. var meshPos = this.mesh.position;
  77902. for (var i = len - 1; i >= 0; i--) {
  77903. var childBone = bones[i];
  77904. var parentBone = childBone.getParent();
  77905. if (!parentBone) {
  77906. continue;
  77907. }
  77908. var points = this._debugLines[boneNum];
  77909. if (!points) {
  77910. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77911. this._debugLines[boneNum] = points;
  77912. }
  77913. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77914. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77915. points[0].subtractInPlace(meshPos);
  77916. points[1].subtractInPlace(meshPos);
  77917. boneNum++;
  77918. }
  77919. };
  77920. SkeletonViewer.prototype.update = function () {
  77921. if (this.autoUpdateBonesMatrices) {
  77922. this.skeleton.computeAbsoluteTransforms();
  77923. }
  77924. if (this.skeleton.bones[0].length === undefined) {
  77925. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77926. }
  77927. else {
  77928. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77929. }
  77930. if (!this._debugMesh) {
  77931. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77932. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77933. }
  77934. else {
  77935. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77936. }
  77937. this._debugMesh.position.copyFrom(this.mesh.position);
  77938. this._debugMesh.color = this.color;
  77939. };
  77940. SkeletonViewer.prototype.dispose = function () {
  77941. if (this._debugMesh) {
  77942. this.isEnabled = false;
  77943. this._debugMesh.dispose();
  77944. this._debugMesh = null;
  77945. }
  77946. };
  77947. return SkeletonViewer;
  77948. }());
  77949. return Debug;
  77950. }());
  77951. BABYLON.Debug = Debug;
  77952. })(BABYLON || (BABYLON = {}));
  77953. //# sourceMappingURL=babylon.debugModules.js.map
  77954. var BABYLON;
  77955. (function (BABYLON) {
  77956. var RayHelper = /** @class */ (function () {
  77957. function RayHelper(ray) {
  77958. this.ray = ray;
  77959. }
  77960. RayHelper.CreateAndShow = function (ray, scene, color) {
  77961. var helper = new RayHelper(ray);
  77962. helper.show(scene, color);
  77963. return helper;
  77964. };
  77965. RayHelper.prototype.show = function (scene, color) {
  77966. if (!this._renderFunction && this.ray) {
  77967. var ray = this.ray;
  77968. this._renderFunction = this._render.bind(this);
  77969. this._scene = scene;
  77970. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  77971. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  77972. if (this._renderFunction) {
  77973. this._scene.registerBeforeRender(this._renderFunction);
  77974. }
  77975. }
  77976. if (color && this._renderLine) {
  77977. this._renderLine.color.copyFrom(color);
  77978. }
  77979. };
  77980. RayHelper.prototype.hide = function () {
  77981. if (this._renderFunction && this._scene) {
  77982. this._scene.unregisterBeforeRender(this._renderFunction);
  77983. this._scene = null;
  77984. this._renderFunction = null;
  77985. if (this._renderLine) {
  77986. this._renderLine.dispose();
  77987. this._renderLine = null;
  77988. }
  77989. this._renderPoints = [];
  77990. }
  77991. };
  77992. RayHelper.prototype._render = function () {
  77993. var ray = this.ray;
  77994. if (!ray) {
  77995. return;
  77996. }
  77997. var point = this._renderPoints[1];
  77998. var len = Math.min(ray.length, 1000000);
  77999. point.copyFrom(ray.direction);
  78000. point.scaleInPlace(len);
  78001. point.addInPlace(ray.origin);
  78002. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78003. };
  78004. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78005. this._attachedToMesh = mesh;
  78006. var ray = this.ray;
  78007. if (!ray) {
  78008. return;
  78009. }
  78010. if (!ray.direction) {
  78011. ray.direction = BABYLON.Vector3.Zero();
  78012. }
  78013. if (!ray.origin) {
  78014. ray.origin = BABYLON.Vector3.Zero();
  78015. }
  78016. if (length) {
  78017. ray.length = length;
  78018. }
  78019. if (!meshSpaceOrigin) {
  78020. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78021. }
  78022. if (!meshSpaceDirection) {
  78023. // -1 so that this will work with Mesh.lookAt
  78024. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78025. }
  78026. if (!this._meshSpaceDirection) {
  78027. this._meshSpaceDirection = meshSpaceDirection.clone();
  78028. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78029. }
  78030. else {
  78031. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78032. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78033. }
  78034. if (!this._updateToMeshFunction) {
  78035. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78036. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78037. }
  78038. this._updateToMesh();
  78039. };
  78040. RayHelper.prototype.detachFromMesh = function () {
  78041. if (this._attachedToMesh) {
  78042. if (this._updateToMeshFunction) {
  78043. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78044. }
  78045. this._attachedToMesh = null;
  78046. this._updateToMeshFunction = null;
  78047. }
  78048. };
  78049. RayHelper.prototype._updateToMesh = function () {
  78050. var ray = this.ray;
  78051. if (!this._attachedToMesh || !ray) {
  78052. return;
  78053. }
  78054. if (this._attachedToMesh._isDisposed) {
  78055. this.detachFromMesh();
  78056. return;
  78057. }
  78058. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78059. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78060. };
  78061. RayHelper.prototype.dispose = function () {
  78062. this.hide();
  78063. this.detachFromMesh();
  78064. this.ray = null;
  78065. };
  78066. return RayHelper;
  78067. }());
  78068. BABYLON.RayHelper = RayHelper;
  78069. })(BABYLON || (BABYLON = {}));
  78070. //# sourceMappingURL=babylon.rayHelper.js.map
  78071. var BABYLON;
  78072. (function (BABYLON) {
  78073. // load the inspector using require, if not present in the global namespace.
  78074. var DebugLayer = /** @class */ (function () {
  78075. function DebugLayer(scene) {
  78076. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78077. this._scene = scene;
  78078. // load inspector using require, if it doesn't exist on the global namespace.
  78079. }
  78080. /** Creates the inspector window. */
  78081. DebugLayer.prototype._createInspector = function (config) {
  78082. if (config === void 0) { config = {}; }
  78083. var popup = config.popup || false;
  78084. var initialTab = config.initialTab || 0;
  78085. var parentElement = config.parentElement || null;
  78086. if (!this._inspector) {
  78087. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78088. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78089. } // else nothing to do,; instance is already existing
  78090. };
  78091. DebugLayer.prototype.isVisible = function () {
  78092. if (!this._inspector) {
  78093. return false;
  78094. }
  78095. return true;
  78096. };
  78097. DebugLayer.prototype.hide = function () {
  78098. if (this._inspector) {
  78099. try {
  78100. this._inspector.dispose();
  78101. }
  78102. catch (e) {
  78103. // If the inspector has been removed directly from the inspector tool
  78104. }
  78105. this._inspector = null;
  78106. }
  78107. };
  78108. DebugLayer.prototype.show = function (config) {
  78109. if (config === void 0) { config = {}; }
  78110. if (typeof this.BJSINSPECTOR == 'undefined') {
  78111. // Load inspector and add it to the DOM
  78112. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78113. }
  78114. else {
  78115. // Otherwise creates the inspector
  78116. this._createInspector(config);
  78117. }
  78118. };
  78119. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78120. return DebugLayer;
  78121. }());
  78122. BABYLON.DebugLayer = DebugLayer;
  78123. })(BABYLON || (BABYLON = {}));
  78124. //# sourceMappingURL=babylon.debugLayer.js.map
  78125. var BABYLON;
  78126. (function (BABYLON) {
  78127. var BoundingBoxRenderer = /** @class */ (function () {
  78128. function BoundingBoxRenderer(scene) {
  78129. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78130. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78131. this.showBackLines = true;
  78132. this.renderList = new BABYLON.SmartArray(32);
  78133. this._vertexBuffers = {};
  78134. this._scene = scene;
  78135. }
  78136. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78137. if (this._colorShader) {
  78138. return;
  78139. }
  78140. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78141. attributes: [BABYLON.VertexBuffer.PositionKind],
  78142. uniforms: ["world", "viewProjection", "color"]
  78143. });
  78144. var engine = this._scene.getEngine();
  78145. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78146. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78147. this._createIndexBuffer();
  78148. };
  78149. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78150. var engine = this._scene.getEngine();
  78151. 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]);
  78152. };
  78153. BoundingBoxRenderer.prototype._rebuild = function () {
  78154. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78155. if (vb) {
  78156. vb._rebuild();
  78157. }
  78158. this._createIndexBuffer();
  78159. };
  78160. BoundingBoxRenderer.prototype.reset = function () {
  78161. this.renderList.reset();
  78162. };
  78163. BoundingBoxRenderer.prototype.render = function () {
  78164. if (this.renderList.length === 0) {
  78165. return;
  78166. }
  78167. this._prepareRessources();
  78168. if (!this._colorShader.isReady()) {
  78169. return;
  78170. }
  78171. var engine = this._scene.getEngine();
  78172. engine.setDepthWrite(false);
  78173. this._colorShader._preBind();
  78174. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78175. var boundingBox = this.renderList.data[boundingBoxIndex];
  78176. var min = boundingBox.minimum;
  78177. var max = boundingBox.maximum;
  78178. var diff = max.subtract(min);
  78179. var median = min.add(diff.scale(0.5));
  78180. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78181. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78182. .multiply(boundingBox.getWorldMatrix());
  78183. // VBOs
  78184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78185. if (this.showBackLines) {
  78186. // Back
  78187. engine.setDepthFunctionToGreaterOrEqual();
  78188. this._scene.resetCachedMaterial();
  78189. this._colorShader.setColor4("color", this.backColor.toColor4());
  78190. this._colorShader.bind(worldMatrix);
  78191. // Draw order
  78192. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78193. }
  78194. // Front
  78195. engine.setDepthFunctionToLess();
  78196. this._scene.resetCachedMaterial();
  78197. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78198. this._colorShader.bind(worldMatrix);
  78199. // Draw order
  78200. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78201. }
  78202. this._colorShader.unbind();
  78203. engine.setDepthFunctionToLessOrEqual();
  78204. engine.setDepthWrite(true);
  78205. };
  78206. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78207. this._prepareRessources();
  78208. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78209. return;
  78210. }
  78211. var engine = this._scene.getEngine();
  78212. engine.setDepthWrite(false);
  78213. engine.setColorWrite(false);
  78214. this._colorShader._preBind();
  78215. var boundingBox = mesh._boundingInfo.boundingBox;
  78216. var min = boundingBox.minimum;
  78217. var max = boundingBox.maximum;
  78218. var diff = max.subtract(min);
  78219. var median = min.add(diff.scale(0.5));
  78220. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78221. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78222. .multiply(boundingBox.getWorldMatrix());
  78223. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78224. engine.setDepthFunctionToLess();
  78225. this._scene.resetCachedMaterial();
  78226. this._colorShader.bind(worldMatrix);
  78227. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78228. this._colorShader.unbind();
  78229. engine.setDepthFunctionToLessOrEqual();
  78230. engine.setDepthWrite(true);
  78231. engine.setColorWrite(true);
  78232. };
  78233. BoundingBoxRenderer.prototype.dispose = function () {
  78234. if (!this._colorShader) {
  78235. return;
  78236. }
  78237. this.renderList.dispose();
  78238. this._colorShader.dispose();
  78239. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78240. if (buffer) {
  78241. buffer.dispose();
  78242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78243. }
  78244. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78245. };
  78246. return BoundingBoxRenderer;
  78247. }());
  78248. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78249. })(BABYLON || (BABYLON = {}));
  78250. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78251. var BABYLON;
  78252. (function (BABYLON) {
  78253. var MorphTarget = /** @class */ (function () {
  78254. function MorphTarget(name, influence) {
  78255. if (influence === void 0) { influence = 0; }
  78256. this.name = name;
  78257. this.animations = new Array();
  78258. this._positions = null;
  78259. this._normals = null;
  78260. this._tangents = null;
  78261. this.onInfluenceChanged = new BABYLON.Observable();
  78262. this.influence = influence;
  78263. }
  78264. Object.defineProperty(MorphTarget.prototype, "influence", {
  78265. get: function () {
  78266. return this._influence;
  78267. },
  78268. set: function (influence) {
  78269. if (this._influence === influence) {
  78270. return;
  78271. }
  78272. var previous = this._influence;
  78273. this._influence = influence;
  78274. if (this.onInfluenceChanged.hasObservers) {
  78275. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78276. }
  78277. },
  78278. enumerable: true,
  78279. configurable: true
  78280. });
  78281. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78282. get: function () {
  78283. return !!this._positions;
  78284. },
  78285. enumerable: true,
  78286. configurable: true
  78287. });
  78288. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78289. get: function () {
  78290. return !!this._normals;
  78291. },
  78292. enumerable: true,
  78293. configurable: true
  78294. });
  78295. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78296. get: function () {
  78297. return !!this._tangents;
  78298. },
  78299. enumerable: true,
  78300. configurable: true
  78301. });
  78302. MorphTarget.prototype.setPositions = function (data) {
  78303. this._positions = data;
  78304. };
  78305. MorphTarget.prototype.getPositions = function () {
  78306. return this._positions;
  78307. };
  78308. MorphTarget.prototype.setNormals = function (data) {
  78309. this._normals = data;
  78310. };
  78311. MorphTarget.prototype.getNormals = function () {
  78312. return this._normals;
  78313. };
  78314. MorphTarget.prototype.setTangents = function (data) {
  78315. this._tangents = data;
  78316. };
  78317. MorphTarget.prototype.getTangents = function () {
  78318. return this._tangents;
  78319. };
  78320. /**
  78321. * Serializes the current target into a Serialization object.
  78322. * Returns the serialized object.
  78323. */
  78324. MorphTarget.prototype.serialize = function () {
  78325. var serializationObject = {};
  78326. serializationObject.name = this.name;
  78327. serializationObject.influence = this.influence;
  78328. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78329. if (this.hasNormals) {
  78330. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78331. }
  78332. if (this.hasTangents) {
  78333. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78334. }
  78335. // Animations
  78336. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78337. return serializationObject;
  78338. };
  78339. // Statics
  78340. MorphTarget.Parse = function (serializationObject) {
  78341. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78342. result.setPositions(serializationObject.positions);
  78343. if (serializationObject.normals) {
  78344. result.setNormals(serializationObject.normals);
  78345. }
  78346. if (serializationObject.tangents) {
  78347. result.setTangents(serializationObject.tangents);
  78348. }
  78349. // Animations
  78350. if (serializationObject.animations) {
  78351. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78352. var parsedAnimation = serializationObject.animations[animationIndex];
  78353. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78354. }
  78355. }
  78356. return result;
  78357. };
  78358. MorphTarget.FromMesh = function (mesh, name, influence) {
  78359. if (!name) {
  78360. name = mesh.name;
  78361. }
  78362. var result = new MorphTarget(name, influence);
  78363. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78364. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78365. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78366. }
  78367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78368. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78369. }
  78370. return result;
  78371. };
  78372. return MorphTarget;
  78373. }());
  78374. BABYLON.MorphTarget = MorphTarget;
  78375. })(BABYLON || (BABYLON = {}));
  78376. //# sourceMappingURL=babylon.morphTarget.js.map
  78377. var BABYLON;
  78378. (function (BABYLON) {
  78379. var MorphTargetManager = /** @class */ (function () {
  78380. function MorphTargetManager(scene) {
  78381. if (scene === void 0) { scene = null; }
  78382. this._targets = new Array();
  78383. this._targetObservable = new Array();
  78384. this._activeTargets = new BABYLON.SmartArray(16);
  78385. this._supportsNormals = false;
  78386. this._supportsTangents = false;
  78387. this._vertexCount = 0;
  78388. this._uniqueId = 0;
  78389. this._tempInfluences = new Array();
  78390. if (!scene) {
  78391. scene = BABYLON.Engine.LastCreatedScene;
  78392. }
  78393. this._scene = scene;
  78394. if (this._scene) {
  78395. this._scene.morphTargetManagers.push(this);
  78396. this._uniqueId = this._scene.getUniqueId();
  78397. }
  78398. }
  78399. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78400. get: function () {
  78401. return this._uniqueId;
  78402. },
  78403. enumerable: true,
  78404. configurable: true
  78405. });
  78406. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78407. get: function () {
  78408. return this._vertexCount;
  78409. },
  78410. enumerable: true,
  78411. configurable: true
  78412. });
  78413. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78414. get: function () {
  78415. return this._supportsNormals;
  78416. },
  78417. enumerable: true,
  78418. configurable: true
  78419. });
  78420. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78421. get: function () {
  78422. return this._supportsTangents;
  78423. },
  78424. enumerable: true,
  78425. configurable: true
  78426. });
  78427. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78428. get: function () {
  78429. return this._targets.length;
  78430. },
  78431. enumerable: true,
  78432. configurable: true
  78433. });
  78434. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78435. get: function () {
  78436. return this._activeTargets.length;
  78437. },
  78438. enumerable: true,
  78439. configurable: true
  78440. });
  78441. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78442. get: function () {
  78443. return this._influences;
  78444. },
  78445. enumerable: true,
  78446. configurable: true
  78447. });
  78448. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78449. return this._activeTargets.data[index];
  78450. };
  78451. MorphTargetManager.prototype.getTarget = function (index) {
  78452. return this._targets[index];
  78453. };
  78454. MorphTargetManager.prototype.addTarget = function (target) {
  78455. var _this = this;
  78456. this._targets.push(target);
  78457. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78458. _this._syncActiveTargets(needUpdate);
  78459. }));
  78460. this._syncActiveTargets(true);
  78461. };
  78462. MorphTargetManager.prototype.removeTarget = function (target) {
  78463. var index = this._targets.indexOf(target);
  78464. if (index >= 0) {
  78465. this._targets.splice(index, 1);
  78466. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78467. this._syncActiveTargets(true);
  78468. }
  78469. };
  78470. /**
  78471. * Serializes the current manager into a Serialization object.
  78472. * Returns the serialized object.
  78473. */
  78474. MorphTargetManager.prototype.serialize = function () {
  78475. var serializationObject = {};
  78476. serializationObject.id = this.uniqueId;
  78477. serializationObject.targets = [];
  78478. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78479. var target = _a[_i];
  78480. serializationObject.targets.push(target.serialize());
  78481. }
  78482. return serializationObject;
  78483. };
  78484. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78485. var influenceCount = 0;
  78486. this._activeTargets.reset();
  78487. this._supportsNormals = true;
  78488. this._supportsTangents = true;
  78489. this._vertexCount = 0;
  78490. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78491. var target = _a[_i];
  78492. this._activeTargets.push(target);
  78493. this._tempInfluences[influenceCount++] = target.influence;
  78494. var positions = target.getPositions();
  78495. if (positions) {
  78496. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78497. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78498. var vertexCount = positions.length / 3;
  78499. if (this._vertexCount === 0) {
  78500. this._vertexCount = vertexCount;
  78501. }
  78502. else if (this._vertexCount !== vertexCount) {
  78503. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78504. return;
  78505. }
  78506. }
  78507. }
  78508. if (!this._influences || this._influences.length !== influenceCount) {
  78509. this._influences = new Float32Array(influenceCount);
  78510. }
  78511. for (var index = 0; index < influenceCount; index++) {
  78512. this._influences[index] = this._tempInfluences[index];
  78513. }
  78514. if (needUpdate && this._scene) {
  78515. // Flag meshes as dirty to resync with the active targets
  78516. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78517. var mesh = _c[_b];
  78518. if (mesh.morphTargetManager === this) {
  78519. mesh._syncGeometryWithMorphTargetManager();
  78520. }
  78521. }
  78522. }
  78523. };
  78524. // Statics
  78525. MorphTargetManager.Parse = function (serializationObject, scene) {
  78526. var result = new MorphTargetManager(scene);
  78527. result._uniqueId = serializationObject.id;
  78528. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78529. var targetData = _a[_i];
  78530. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78531. }
  78532. return result;
  78533. };
  78534. return MorphTargetManager;
  78535. }());
  78536. BABYLON.MorphTargetManager = MorphTargetManager;
  78537. })(BABYLON || (BABYLON = {}));
  78538. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78539. var BABYLON;
  78540. (function (BABYLON) {
  78541. var Octree = /** @class */ (function () {
  78542. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78543. if (maxDepth === void 0) { maxDepth = 2; }
  78544. this.maxDepth = maxDepth;
  78545. this.dynamicContent = new Array();
  78546. this._maxBlockCapacity = maxBlockCapacity || 64;
  78547. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78548. this._creationFunc = creationFunc;
  78549. }
  78550. // Methods
  78551. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78552. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78553. };
  78554. Octree.prototype.addMesh = function (entry) {
  78555. for (var index = 0; index < this.blocks.length; index++) {
  78556. var block = this.blocks[index];
  78557. block.addEntry(entry);
  78558. }
  78559. };
  78560. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78561. this._selectionContent.reset();
  78562. for (var index = 0; index < this.blocks.length; index++) {
  78563. var block = this.blocks[index];
  78564. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78565. }
  78566. if (allowDuplicate) {
  78567. this._selectionContent.concat(this.dynamicContent);
  78568. }
  78569. else {
  78570. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78571. }
  78572. return this._selectionContent;
  78573. };
  78574. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78575. this._selectionContent.reset();
  78576. for (var index = 0; index < this.blocks.length; index++) {
  78577. var block = this.blocks[index];
  78578. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78579. }
  78580. if (allowDuplicate) {
  78581. this._selectionContent.concat(this.dynamicContent);
  78582. }
  78583. else {
  78584. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78585. }
  78586. return this._selectionContent;
  78587. };
  78588. Octree.prototype.intersectsRay = function (ray) {
  78589. this._selectionContent.reset();
  78590. for (var index = 0; index < this.blocks.length; index++) {
  78591. var block = this.blocks[index];
  78592. block.intersectsRay(ray, this._selectionContent);
  78593. }
  78594. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78595. return this._selectionContent;
  78596. };
  78597. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78598. target.blocks = new Array();
  78599. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78600. // Segmenting space
  78601. for (var x = 0; x < 2; x++) {
  78602. for (var y = 0; y < 2; y++) {
  78603. for (var z = 0; z < 2; z++) {
  78604. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78605. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78606. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78607. block.addEntries(entries);
  78608. target.blocks.push(block);
  78609. }
  78610. }
  78611. }
  78612. };
  78613. Octree.CreationFuncForMeshes = function (entry, block) {
  78614. var boundingInfo = entry.getBoundingInfo();
  78615. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78616. block.entries.push(entry);
  78617. }
  78618. };
  78619. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78620. var boundingInfo = entry.getBoundingInfo();
  78621. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78622. block.entries.push(entry);
  78623. }
  78624. };
  78625. return Octree;
  78626. }());
  78627. BABYLON.Octree = Octree;
  78628. })(BABYLON || (BABYLON = {}));
  78629. //# sourceMappingURL=babylon.octree.js.map
  78630. var BABYLON;
  78631. (function (BABYLON) {
  78632. var OctreeBlock = /** @class */ (function () {
  78633. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78634. this.entries = new Array();
  78635. this._boundingVectors = new Array();
  78636. this._capacity = capacity;
  78637. this._depth = depth;
  78638. this._maxDepth = maxDepth;
  78639. this._creationFunc = creationFunc;
  78640. this._minPoint = minPoint;
  78641. this._maxPoint = maxPoint;
  78642. this._boundingVectors.push(minPoint.clone());
  78643. this._boundingVectors.push(maxPoint.clone());
  78644. this._boundingVectors.push(minPoint.clone());
  78645. this._boundingVectors[2].x = maxPoint.x;
  78646. this._boundingVectors.push(minPoint.clone());
  78647. this._boundingVectors[3].y = maxPoint.y;
  78648. this._boundingVectors.push(minPoint.clone());
  78649. this._boundingVectors[4].z = maxPoint.z;
  78650. this._boundingVectors.push(maxPoint.clone());
  78651. this._boundingVectors[5].z = minPoint.z;
  78652. this._boundingVectors.push(maxPoint.clone());
  78653. this._boundingVectors[6].x = minPoint.x;
  78654. this._boundingVectors.push(maxPoint.clone());
  78655. this._boundingVectors[7].y = minPoint.y;
  78656. }
  78657. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78658. // Property
  78659. get: function () {
  78660. return this._capacity;
  78661. },
  78662. enumerable: true,
  78663. configurable: true
  78664. });
  78665. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78666. get: function () {
  78667. return this._minPoint;
  78668. },
  78669. enumerable: true,
  78670. configurable: true
  78671. });
  78672. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78673. get: function () {
  78674. return this._maxPoint;
  78675. },
  78676. enumerable: true,
  78677. configurable: true
  78678. });
  78679. // Methods
  78680. OctreeBlock.prototype.addEntry = function (entry) {
  78681. if (this.blocks) {
  78682. for (var index = 0; index < this.blocks.length; index++) {
  78683. var block = this.blocks[index];
  78684. block.addEntry(entry);
  78685. }
  78686. return;
  78687. }
  78688. this._creationFunc(entry, this);
  78689. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78690. this.createInnerBlocks();
  78691. }
  78692. };
  78693. OctreeBlock.prototype.addEntries = function (entries) {
  78694. for (var index = 0; index < entries.length; index++) {
  78695. var mesh = entries[index];
  78696. this.addEntry(mesh);
  78697. }
  78698. };
  78699. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78700. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78701. if (this.blocks) {
  78702. for (var index = 0; index < this.blocks.length; index++) {
  78703. var block = this.blocks[index];
  78704. block.select(frustumPlanes, selection, allowDuplicate);
  78705. }
  78706. return;
  78707. }
  78708. if (allowDuplicate) {
  78709. selection.concat(this.entries);
  78710. }
  78711. else {
  78712. selection.concatWithNoDuplicate(this.entries);
  78713. }
  78714. }
  78715. };
  78716. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78717. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78718. if (this.blocks) {
  78719. for (var index = 0; index < this.blocks.length; index++) {
  78720. var block = this.blocks[index];
  78721. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78722. }
  78723. return;
  78724. }
  78725. if (allowDuplicate) {
  78726. selection.concat(this.entries);
  78727. }
  78728. else {
  78729. selection.concatWithNoDuplicate(this.entries);
  78730. }
  78731. }
  78732. };
  78733. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78734. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78735. if (this.blocks) {
  78736. for (var index = 0; index < this.blocks.length; index++) {
  78737. var block = this.blocks[index];
  78738. block.intersectsRay(ray, selection);
  78739. }
  78740. return;
  78741. }
  78742. selection.concatWithNoDuplicate(this.entries);
  78743. }
  78744. };
  78745. OctreeBlock.prototype.createInnerBlocks = function () {
  78746. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78747. };
  78748. return OctreeBlock;
  78749. }());
  78750. BABYLON.OctreeBlock = OctreeBlock;
  78751. })(BABYLON || (BABYLON = {}));
  78752. //# sourceMappingURL=babylon.octreeBlock.js.map
  78753. var BABYLON;
  78754. (function (BABYLON) {
  78755. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78756. __extends(VRDistortionCorrectionPostProcess, _super);
  78757. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78758. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78759. 'LensCenter',
  78760. 'Scale',
  78761. 'ScaleIn',
  78762. 'HmdWarpParam'
  78763. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78764. _this._isRightEye = isRightEye;
  78765. _this._distortionFactors = vrMetrics.distortionK;
  78766. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78767. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78768. _this.adaptScaleToCurrentViewport = true;
  78769. _this.onSizeChangedObservable.add(function () {
  78770. _this.aspectRatio = _this.width * .5 / _this.height;
  78771. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78772. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78773. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78774. });
  78775. _this.onApplyObservable.add(function (effect) {
  78776. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78777. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78778. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78779. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78780. });
  78781. return _this;
  78782. }
  78783. return VRDistortionCorrectionPostProcess;
  78784. }(BABYLON.PostProcess));
  78785. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78786. })(BABYLON || (BABYLON = {}));
  78787. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78788. var BABYLON;
  78789. (function (BABYLON) {
  78790. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78791. __extends(AnaglyphPostProcess, _super);
  78792. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78793. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78794. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78795. _this.onApplyObservable.add(function (effect) {
  78796. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78797. });
  78798. return _this;
  78799. }
  78800. return AnaglyphPostProcess;
  78801. }(BABYLON.PostProcess));
  78802. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78803. })(BABYLON || (BABYLON = {}));
  78804. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78805. var BABYLON;
  78806. (function (BABYLON) {
  78807. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78808. __extends(StereoscopicInterlacePostProcess, _super);
  78809. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78810. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78811. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78812. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78813. _this.onSizeChangedObservable.add(function () {
  78814. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78815. });
  78816. _this.onApplyObservable.add(function (effect) {
  78817. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78818. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78819. });
  78820. return _this;
  78821. }
  78822. return StereoscopicInterlacePostProcess;
  78823. }(BABYLON.PostProcess));
  78824. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78825. })(BABYLON || (BABYLON = {}));
  78826. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78827. var BABYLON;
  78828. (function (BABYLON) {
  78829. /**
  78830. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78831. * Screen rotation is taken into account.
  78832. */
  78833. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78834. function FreeCameraDeviceOrientationInput() {
  78835. var _this = this;
  78836. this._screenOrientationAngle = 0;
  78837. this._screenQuaternion = new BABYLON.Quaternion();
  78838. this._alpha = 0;
  78839. this._beta = 0;
  78840. this._gamma = 0;
  78841. this._orientationChanged = function () {
  78842. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78843. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78844. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78845. };
  78846. this._deviceOrientation = function (evt) {
  78847. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78848. _this._beta = evt.beta !== null ? evt.beta : 0;
  78849. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78850. };
  78851. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78852. this._orientationChanged();
  78853. }
  78854. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78855. get: function () {
  78856. return this._camera;
  78857. },
  78858. set: function (camera) {
  78859. this._camera = camera;
  78860. if (this._camera != null && !this._camera.rotationQuaternion) {
  78861. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78862. }
  78863. },
  78864. enumerable: true,
  78865. configurable: true
  78866. });
  78867. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78868. window.addEventListener("orientationchange", this._orientationChanged);
  78869. window.addEventListener("deviceorientation", this._deviceOrientation);
  78870. //In certain cases, the attach control is called AFTER orientation was changed,
  78871. //So this is needed.
  78872. this._orientationChanged();
  78873. };
  78874. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78875. window.removeEventListener("orientationchange", this._orientationChanged);
  78876. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78877. };
  78878. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78879. //if no device orientation provided, don't update the rotation.
  78880. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78881. if (!this._alpha)
  78882. return;
  78883. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78884. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78885. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78886. //Mirror on XY Plane
  78887. this._camera.rotationQuaternion.z *= -1;
  78888. this._camera.rotationQuaternion.w *= -1;
  78889. };
  78890. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78891. return "FreeCameraDeviceOrientationInput";
  78892. };
  78893. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78894. return "deviceOrientation";
  78895. };
  78896. return FreeCameraDeviceOrientationInput;
  78897. }());
  78898. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78899. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78900. })(BABYLON || (BABYLON = {}));
  78901. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78902. var BABYLON;
  78903. (function (BABYLON) {
  78904. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78905. function ArcRotateCameraVRDeviceOrientationInput() {
  78906. this.alphaCorrection = 1;
  78907. this.betaCorrection = 1;
  78908. this.gammaCorrection = 1;
  78909. this._alpha = 0;
  78910. this._gamma = 0;
  78911. this._dirty = false;
  78912. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78913. }
  78914. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78915. this.camera.attachControl(element, noPreventDefault);
  78916. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78917. };
  78918. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78919. if (evt.alpha !== null) {
  78920. this._alpha = +evt.alpha | 0;
  78921. }
  78922. if (evt.gamma !== null) {
  78923. this._gamma = +evt.gamma | 0;
  78924. }
  78925. this._dirty = true;
  78926. };
  78927. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78928. if (this._dirty) {
  78929. this._dirty = false;
  78930. if (this._gamma < 0) {
  78931. this._gamma = 180 + this._gamma;
  78932. }
  78933. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78934. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78935. }
  78936. };
  78937. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78938. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78939. };
  78940. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78941. return "ArcRotateCameraVRDeviceOrientationInput";
  78942. };
  78943. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  78944. return "VRDeviceOrientation";
  78945. };
  78946. return ArcRotateCameraVRDeviceOrientationInput;
  78947. }());
  78948. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  78949. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  78950. })(BABYLON || (BABYLON = {}));
  78951. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  78952. var BABYLON;
  78953. (function (BABYLON) {
  78954. var VRCameraMetrics = /** @class */ (function () {
  78955. function VRCameraMetrics() {
  78956. this.compensateDistortion = true;
  78957. }
  78958. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  78959. get: function () {
  78960. return this.hResolution / (2 * this.vResolution);
  78961. },
  78962. enumerable: true,
  78963. configurable: true
  78964. });
  78965. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  78966. get: function () {
  78967. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  78968. },
  78969. enumerable: true,
  78970. configurable: true
  78971. });
  78972. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  78973. get: function () {
  78974. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78975. var h = (4 * meters) / this.hScreenSize;
  78976. return BABYLON.Matrix.Translation(h, 0, 0);
  78977. },
  78978. enumerable: true,
  78979. configurable: true
  78980. });
  78981. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  78982. get: function () {
  78983. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78984. var h = (4 * meters) / this.hScreenSize;
  78985. return BABYLON.Matrix.Translation(-h, 0, 0);
  78986. },
  78987. enumerable: true,
  78988. configurable: true
  78989. });
  78990. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  78991. get: function () {
  78992. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  78993. },
  78994. enumerable: true,
  78995. configurable: true
  78996. });
  78997. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  78998. get: function () {
  78999. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79000. },
  79001. enumerable: true,
  79002. configurable: true
  79003. });
  79004. VRCameraMetrics.GetDefault = function () {
  79005. var result = new VRCameraMetrics();
  79006. result.hResolution = 1280;
  79007. result.vResolution = 800;
  79008. result.hScreenSize = 0.149759993;
  79009. result.vScreenSize = 0.0935999975;
  79010. result.vScreenCenter = 0.0467999987;
  79011. result.eyeToScreenDistance = 0.0410000011;
  79012. result.lensSeparationDistance = 0.0635000020;
  79013. result.interpupillaryDistance = 0.0640000030;
  79014. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79015. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79016. result.postProcessScaleFactor = 1.714605507808412;
  79017. result.lensCenterOffset = 0.151976421;
  79018. return result;
  79019. };
  79020. return VRCameraMetrics;
  79021. }());
  79022. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79023. })(BABYLON || (BABYLON = {}));
  79024. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79025. var BABYLON;
  79026. (function (BABYLON) {
  79027. /**
  79028. * This represents a WebVR camera.
  79029. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79030. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79031. */
  79032. var WebVRFreeCamera = /** @class */ (function (_super) {
  79033. __extends(WebVRFreeCamera, _super);
  79034. /**
  79035. * Instantiates a WebVRFreeCamera.
  79036. * @param name The name of the WebVRFreeCamera
  79037. * @param position The starting anchor position for the camera
  79038. * @param scene The scene the camera belongs to
  79039. * @param webVROptions a set of customizable options for the webVRCamera
  79040. */
  79041. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79042. if (webVROptions === void 0) { webVROptions = {}; }
  79043. var _this = _super.call(this, name, position, scene) || this;
  79044. _this.webVROptions = webVROptions;
  79045. /**
  79046. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79047. */
  79048. _this._vrDevice = null;
  79049. /**
  79050. * The rawPose of the vrDevice.
  79051. */
  79052. _this.rawPose = null;
  79053. _this._specsVersion = "1.1";
  79054. _this._attached = false;
  79055. _this._descendants = [];
  79056. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79057. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79058. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79059. _this._standingMatrix = null;
  79060. /**
  79061. * Represents device position in babylon space.
  79062. */
  79063. _this.devicePosition = BABYLON.Vector3.Zero();
  79064. /**
  79065. * Represents device rotation in babylon space.
  79066. */
  79067. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79068. /**
  79069. * The scale of the device to be used when translating from device space to babylon space.
  79070. */
  79071. _this.deviceScaleFactor = 1;
  79072. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79073. _this._worldToDevice = BABYLON.Matrix.Identity();
  79074. /**
  79075. * References to the webVR controllers for the vrDevice.
  79076. */
  79077. _this.controllers = [];
  79078. /**
  79079. * Emits an event when a controller is attached.
  79080. */
  79081. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79082. /**
  79083. * Emits an event when a controller's mesh has been loaded;
  79084. */
  79085. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79086. /**
  79087. * If the rig cameras be used as parent instead of this camera.
  79088. */
  79089. _this.rigParenting = true;
  79090. _this._defaultHeight = undefined;
  79091. _this._workingVector = BABYLON.Vector3.Zero();
  79092. _this._oneVector = BABYLON.Vector3.One();
  79093. _this._workingMatrix = BABYLON.Matrix.Identity();
  79094. _this._cache.position = BABYLON.Vector3.Zero();
  79095. if (webVROptions.defaultHeight) {
  79096. _this._defaultHeight = webVROptions.defaultHeight;
  79097. _this.position.y = _this._defaultHeight;
  79098. }
  79099. _this.minZ = 0.1;
  79100. //legacy support - the compensation boolean was removed.
  79101. if (arguments.length === 5) {
  79102. _this.webVROptions = arguments[4];
  79103. }
  79104. // default webVR options
  79105. if (_this.webVROptions.trackPosition == undefined) {
  79106. _this.webVROptions.trackPosition = true;
  79107. }
  79108. if (_this.webVROptions.controllerMeshes == undefined) {
  79109. _this.webVROptions.controllerMeshes = true;
  79110. }
  79111. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79112. _this.webVROptions.defaultLightingOnControllers = true;
  79113. }
  79114. _this.rotationQuaternion = new BABYLON.Quaternion();
  79115. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79116. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79117. }
  79118. //enable VR
  79119. var engine = _this.getEngine();
  79120. _this._onVREnabled = function (success) { if (success) {
  79121. _this.initControllers();
  79122. } };
  79123. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79124. engine.initWebVR().add(function (event) {
  79125. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79126. return;
  79127. }
  79128. _this._vrDevice = event.vrDisplay;
  79129. //reset the rig parameters.
  79130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79131. if (_this._attached) {
  79132. _this.getEngine().enableVR();
  79133. }
  79134. });
  79135. if (typeof (VRFrameData) !== "undefined")
  79136. _this._frameData = new VRFrameData();
  79137. /**
  79138. * The idea behind the following lines:
  79139. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79140. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79141. * the second will not show it correctly.
  79142. *
  79143. * To solve this - each object that has the camera as parent will be added to a protected array.
  79144. * When the rig camera renders, it will take this array and set all of those to be its children.
  79145. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79146. * Amazing!
  79147. */
  79148. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79149. if (camera.parent === _this && _this.rigParenting) {
  79150. _this._descendants = _this.getDescendants(true, function (n) {
  79151. // don't take the cameras or the controllers!
  79152. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79153. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79154. return !isController && !isRigCamera;
  79155. });
  79156. _this._descendants.forEach(function (node) {
  79157. node.parent = camera;
  79158. });
  79159. }
  79160. });
  79161. scene.onAfterCameraRenderObservable.add(function (camera) {
  79162. if (camera.parent === _this && _this.rigParenting) {
  79163. _this._descendants.forEach(function (node) {
  79164. node.parent = _this;
  79165. });
  79166. }
  79167. });
  79168. return _this;
  79169. }
  79170. /**
  79171. * Gets the device distance from the ground in meters.
  79172. * @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.
  79173. */
  79174. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79175. if (this._standingMatrix) {
  79176. // Add standing matrix offset to get real offset from ground in room
  79177. this._standingMatrix.getTranslationToRef(this._workingVector);
  79178. return this._deviceRoomPosition.y + this._workingVector.y;
  79179. }
  79180. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79181. return this._defaultHeight || 0;
  79182. };
  79183. /**
  79184. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79185. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79186. */
  79187. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79188. var _this = this;
  79189. if (callback === void 0) { callback = function (bool) { }; }
  79190. // Use standing matrix if available
  79191. this.getEngine().initWebVRAsync().then(function (result) {
  79192. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79193. callback(false);
  79194. }
  79195. else {
  79196. _this._standingMatrix = new BABYLON.Matrix();
  79197. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79198. if (!_this.getScene().useRightHandedSystem) {
  79199. [2, 6, 8, 9, 14].forEach(function (num) {
  79200. if (_this._standingMatrix) {
  79201. _this._standingMatrix.m[num] *= -1;
  79202. }
  79203. });
  79204. }
  79205. callback(true);
  79206. }
  79207. });
  79208. };
  79209. /**
  79210. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79211. * @returns A promise with a boolean set to if the standing matrix is supported.
  79212. */
  79213. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79214. var _this = this;
  79215. return new Promise(function (res, rej) {
  79216. _this.useStandingMatrix(function (supported) {
  79217. res(supported);
  79218. });
  79219. });
  79220. };
  79221. /**
  79222. * Disposes the camera
  79223. */
  79224. WebVRFreeCamera.prototype.dispose = function () {
  79225. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79226. _super.prototype.dispose.call(this);
  79227. };
  79228. /**
  79229. * Gets a vrController by name.
  79230. * @param name The name of the controller to retreive
  79231. * @returns the controller matching the name specified or null if not found
  79232. */
  79233. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79234. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79235. var gp = _a[_i];
  79236. if (gp.hand === name) {
  79237. return gp;
  79238. }
  79239. }
  79240. return null;
  79241. };
  79242. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79243. /**
  79244. * The controller corrisponding to the users left hand.
  79245. */
  79246. get: function () {
  79247. if (!this._leftController) {
  79248. this._leftController = this.getControllerByName("left");
  79249. }
  79250. return this._leftController;
  79251. },
  79252. enumerable: true,
  79253. configurable: true
  79254. });
  79255. ;
  79256. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79257. /**
  79258. * The controller corrisponding to the users right hand.
  79259. */
  79260. get: function () {
  79261. if (!this._rightController) {
  79262. this._rightController = this.getControllerByName("right");
  79263. }
  79264. return this._rightController;
  79265. },
  79266. enumerable: true,
  79267. configurable: true
  79268. });
  79269. ;
  79270. /**
  79271. * Casts a ray forward from the vrCamera's gaze.
  79272. * @param length Length of the ray (default: 100)
  79273. * @returns the ray corrisponding to the gaze
  79274. */
  79275. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79276. if (length === void 0) { length = 100; }
  79277. if (this.leftCamera) {
  79278. // Use left eye to avoid computation to compute center on every call
  79279. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79280. }
  79281. else {
  79282. return _super.prototype.getForwardRay.call(this, length);
  79283. }
  79284. };
  79285. /**
  79286. * Updates the camera based on device's frame data
  79287. */
  79288. WebVRFreeCamera.prototype._checkInputs = function () {
  79289. if (this._vrDevice && this._vrDevice.isPresenting) {
  79290. this._vrDevice.getFrameData(this._frameData);
  79291. this.updateFromDevice(this._frameData.pose);
  79292. }
  79293. _super.prototype._checkInputs.call(this);
  79294. };
  79295. /**
  79296. * Updates the poseControlled values based on the input device pose.
  79297. * @param poseData Pose coming from the device
  79298. */
  79299. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79300. if (poseData && poseData.orientation) {
  79301. this.rawPose = poseData;
  79302. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79303. if (this.getScene().useRightHandedSystem) {
  79304. this._deviceRoomRotationQuaternion.z *= -1;
  79305. this._deviceRoomRotationQuaternion.w *= -1;
  79306. }
  79307. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79308. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79309. if (this.getScene().useRightHandedSystem) {
  79310. this._deviceRoomPosition.z *= -1;
  79311. }
  79312. }
  79313. }
  79314. };
  79315. /**
  79316. * WebVR's attach control will start broadcasting frames to the device.
  79317. * Note that in certain browsers (chrome for example) this function must be called
  79318. * within a user-interaction callback. Example:
  79319. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79320. *
  79321. * @param element html element to attach the vrDevice to
  79322. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79323. */
  79324. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79325. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79326. this._attached = true;
  79327. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79328. if (this._vrDevice) {
  79329. this.getEngine().enableVR();
  79330. }
  79331. };
  79332. /**
  79333. * Detaches the camera from the html element and disables VR
  79334. *
  79335. * @param element html element to detach from
  79336. */
  79337. WebVRFreeCamera.prototype.detachControl = function (element) {
  79338. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79339. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79340. _super.prototype.detachControl.call(this, element);
  79341. this._attached = false;
  79342. this.getEngine().disableVR();
  79343. };
  79344. /**
  79345. * @returns the name of this class
  79346. */
  79347. WebVRFreeCamera.prototype.getClassName = function () {
  79348. return "WebVRFreeCamera";
  79349. };
  79350. /**
  79351. * Calls resetPose on the vrDisplay
  79352. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79353. */
  79354. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79355. //uses the vrDisplay's "resetPose()".
  79356. //pitch and roll won't be affected.
  79357. this._vrDevice.resetPose();
  79358. };
  79359. /**
  79360. * Updates the rig cameras (left and right eye)
  79361. */
  79362. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79363. var camLeft = this._rigCameras[0];
  79364. var camRight = this._rigCameras[1];
  79365. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79366. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79367. camLeft.position.copyFrom(this._deviceRoomPosition);
  79368. camRight.position.copyFrom(this._deviceRoomPosition);
  79369. };
  79370. /**
  79371. * Updates the cached values of the camera
  79372. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79373. */
  79374. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79375. var _this = this;
  79376. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79377. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79378. if (!this.updateCacheCalled) {
  79379. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79380. this.updateCacheCalled = true;
  79381. this.update();
  79382. }
  79383. // Set working vector to the device position in room space rotated by the new rotation
  79384. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79385. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79386. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79387. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79388. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79389. // Add translation from anchor position
  79390. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79391. this._workingVector.addInPlace(this.position);
  79392. this._workingVector.subtractInPlace(this._cache.position);
  79393. this._deviceToWorld.setTranslation(this._workingVector);
  79394. // Set an inverted matrix to be used when updating the camera
  79395. this._deviceToWorld.invertToRef(this._worldToDevice);
  79396. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79397. this.controllers.forEach(function (controller) {
  79398. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79399. controller.update();
  79400. });
  79401. }
  79402. if (!ignoreParentClass) {
  79403. _super.prototype._updateCache.call(this);
  79404. }
  79405. this.updateCacheCalled = false;
  79406. };
  79407. /**
  79408. * Updates the current device position and rotation in the babylon world
  79409. */
  79410. WebVRFreeCamera.prototype.update = function () {
  79411. // Get current device position in babylon world
  79412. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79413. // Get current device rotation in babylon world
  79414. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79415. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79416. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79417. _super.prototype.update.call(this);
  79418. };
  79419. /**
  79420. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79421. * @returns an identity matrix
  79422. */
  79423. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79424. return BABYLON.Matrix.Identity();
  79425. };
  79426. /**
  79427. * This function is called by the two RIG cameras.
  79428. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79429. */
  79430. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79431. var _this = this;
  79432. // Update the parent camera prior to using a child camera to avoid desynchronization
  79433. var parentCamera = this._cameraRigParams["parentCamera"];
  79434. parentCamera._updateCache();
  79435. //WebVR 1.1
  79436. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79437. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79438. if (!this.getScene().useRightHandedSystem) {
  79439. [2, 6, 8, 9, 14].forEach(function (num) {
  79440. _this._webvrViewMatrix.m[num] *= -1;
  79441. });
  79442. }
  79443. // update the camera rotation matrix
  79444. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79445. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79446. // Computing target and final matrix
  79447. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79448. // should the view matrix be updated with scale and position offset?
  79449. if (parentCamera.deviceScaleFactor !== 1) {
  79450. this._webvrViewMatrix.invert();
  79451. // scale the position, if set
  79452. if (parentCamera.deviceScaleFactor) {
  79453. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79454. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79455. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79456. }
  79457. this._webvrViewMatrix.invert();
  79458. }
  79459. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79460. return this._webvrViewMatrix;
  79461. };
  79462. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79463. var _this = this;
  79464. var parentCamera = this.parent;
  79465. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79466. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79467. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79468. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79469. //babylon compatible matrix
  79470. if (!this.getScene().useRightHandedSystem) {
  79471. [8, 9, 10, 11].forEach(function (num) {
  79472. _this._projectionMatrix.m[num] *= -1;
  79473. });
  79474. }
  79475. return this._projectionMatrix;
  79476. };
  79477. /**
  79478. * Initializes the controllers and their meshes
  79479. */
  79480. WebVRFreeCamera.prototype.initControllers = function () {
  79481. var _this = this;
  79482. this.controllers = [];
  79483. var manager = this.getScene().gamepadManager;
  79484. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79485. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79486. var webVrController = gamepad;
  79487. if (webVrController.defaultModel) {
  79488. webVrController.defaultModel.setEnabled(false);
  79489. }
  79490. if (webVrController.hand === "right") {
  79491. _this._rightController = null;
  79492. }
  79493. if (webVrController.hand === "left") {
  79494. _this._leftController = null;
  79495. }
  79496. var controllerIndex = _this.controllers.indexOf(webVrController);
  79497. if (controllerIndex !== -1) {
  79498. _this.controllers.splice(controllerIndex, 1);
  79499. }
  79500. }
  79501. });
  79502. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79503. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79504. var webVrController_1 = gamepad;
  79505. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79506. if (_this.webVROptions.controllerMeshes) {
  79507. if (webVrController_1.defaultModel) {
  79508. webVrController_1.defaultModel.setEnabled(true);
  79509. }
  79510. else {
  79511. // Load the meshes
  79512. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79513. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79514. if (_this.webVROptions.defaultLightingOnControllers) {
  79515. if (!_this._lightOnControllers) {
  79516. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79517. }
  79518. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79519. var children = mesh.getChildren();
  79520. if (children.length !== 0) {
  79521. children.forEach(function (mesh) {
  79522. light.includedOnlyMeshes.push(mesh);
  79523. activateLightOnSubMeshes_1(mesh, light);
  79524. });
  79525. }
  79526. };
  79527. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79528. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79529. }
  79530. });
  79531. }
  79532. }
  79533. webVrController_1.attachToPoseControlledCamera(_this);
  79534. // since this is async - sanity check. Is the controller already stored?
  79535. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79536. //add to the controllers array
  79537. _this.controllers.push(webVrController_1);
  79538. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79539. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79540. // So we're overriding setting left & right manually to be sure
  79541. var firstViveWandDetected = false;
  79542. for (var i = 0; i < _this.controllers.length; i++) {
  79543. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79544. if (!firstViveWandDetected) {
  79545. firstViveWandDetected = true;
  79546. _this.controllers[i].hand = "left";
  79547. }
  79548. else {
  79549. _this.controllers[i].hand = "right";
  79550. }
  79551. }
  79552. }
  79553. //did we find enough controllers? Great! let the developer know.
  79554. if (_this.controllers.length >= 2) {
  79555. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79556. }
  79557. }
  79558. }
  79559. });
  79560. };
  79561. return WebVRFreeCamera;
  79562. }(BABYLON.FreeCamera));
  79563. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79564. })(BABYLON || (BABYLON = {}));
  79565. //# sourceMappingURL=babylon.webVRCamera.js.map
  79566. var BABYLON;
  79567. (function (BABYLON) {
  79568. // We're mainly based on the logic defined into the FreeCamera code
  79569. /**
  79570. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79571. * being tilted forward or back and left or right.
  79572. */
  79573. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79574. __extends(DeviceOrientationCamera, _super);
  79575. /**
  79576. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79577. * @param name The name of the camera
  79578. * @param position The start position camera
  79579. * @param scene The scene the camera belongs to
  79580. */
  79581. function DeviceOrientationCamera(name, position, scene) {
  79582. var _this = _super.call(this, name, position, scene) || this;
  79583. _this._quaternionCache = new BABYLON.Quaternion();
  79584. _this.inputs.addDeviceOrientation();
  79585. return _this;
  79586. }
  79587. /**
  79588. * Gets the current instance class name ("DeviceOrientationCamera").
  79589. * This helps avoiding instanceof at run time.
  79590. * @returns the class name
  79591. */
  79592. DeviceOrientationCamera.prototype.getClassName = function () {
  79593. return "DeviceOrientationCamera";
  79594. };
  79595. /**
  79596. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79597. */
  79598. DeviceOrientationCamera.prototype._checkInputs = function () {
  79599. _super.prototype._checkInputs.call(this);
  79600. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79601. if (this._initialQuaternion) {
  79602. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79603. }
  79604. };
  79605. /**
  79606. * Reset the camera to its default orientation on the specified axis only.
  79607. * @param axis The axis to reset
  79608. */
  79609. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79610. var _this = this;
  79611. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79612. //can only work if this camera has a rotation quaternion already.
  79613. if (!this.rotationQuaternion)
  79614. return;
  79615. if (!this._initialQuaternion) {
  79616. this._initialQuaternion = new BABYLON.Quaternion();
  79617. }
  79618. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79619. ['x', 'y', 'z'].forEach(function (axisName) {
  79620. if (!axis[axisName]) {
  79621. _this._initialQuaternion[axisName] = 0;
  79622. }
  79623. else {
  79624. _this._initialQuaternion[axisName] *= -1;
  79625. }
  79626. });
  79627. this._initialQuaternion.normalize();
  79628. //force rotation update
  79629. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79630. };
  79631. return DeviceOrientationCamera;
  79632. }(BABYLON.FreeCamera));
  79633. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79634. })(BABYLON || (BABYLON = {}));
  79635. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79636. var BABYLON;
  79637. (function (BABYLON) {
  79638. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79639. __extends(VRDeviceOrientationFreeCamera, _super);
  79640. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79641. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79642. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79643. var _this = _super.call(this, name, position, scene) || this;
  79644. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79645. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79646. return _this;
  79647. }
  79648. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79649. return "VRDeviceOrientationFreeCamera";
  79650. };
  79651. return VRDeviceOrientationFreeCamera;
  79652. }(BABYLON.DeviceOrientationCamera));
  79653. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79654. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79655. __extends(VRDeviceOrientationGamepadCamera, _super);
  79656. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79657. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79658. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79659. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79660. _this.inputs.addGamepad();
  79661. return _this;
  79662. }
  79663. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79664. return "VRDeviceOrientationGamepadCamera";
  79665. };
  79666. return VRDeviceOrientationGamepadCamera;
  79667. }(VRDeviceOrientationFreeCamera));
  79668. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79669. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79670. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79671. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79672. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79673. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79674. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79675. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79676. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79677. _this.inputs.addVRDeviceOrientation();
  79678. return _this;
  79679. }
  79680. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79681. return "VRDeviceOrientationArcRotateCamera";
  79682. };
  79683. return VRDeviceOrientationArcRotateCamera;
  79684. }(BABYLON.ArcRotateCamera));
  79685. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79686. })(BABYLON || (BABYLON = {}));
  79687. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79688. var BABYLON;
  79689. (function (BABYLON) {
  79690. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79691. __extends(AnaglyphFreeCamera, _super);
  79692. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79693. var _this = _super.call(this, name, position, scene) || this;
  79694. _this.interaxialDistance = interaxialDistance;
  79695. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79696. return _this;
  79697. }
  79698. AnaglyphFreeCamera.prototype.getClassName = function () {
  79699. return "AnaglyphFreeCamera";
  79700. };
  79701. return AnaglyphFreeCamera;
  79702. }(BABYLON.FreeCamera));
  79703. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79704. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79705. __extends(AnaglyphArcRotateCamera, _super);
  79706. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79707. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79708. _this.interaxialDistance = interaxialDistance;
  79709. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79710. return _this;
  79711. }
  79712. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79713. return "AnaglyphArcRotateCamera";
  79714. };
  79715. return AnaglyphArcRotateCamera;
  79716. }(BABYLON.ArcRotateCamera));
  79717. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79718. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79719. __extends(AnaglyphGamepadCamera, _super);
  79720. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79721. var _this = _super.call(this, name, position, scene) || this;
  79722. _this.interaxialDistance = interaxialDistance;
  79723. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79724. return _this;
  79725. }
  79726. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79727. return "AnaglyphGamepadCamera";
  79728. };
  79729. return AnaglyphGamepadCamera;
  79730. }(BABYLON.GamepadCamera));
  79731. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79732. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79733. __extends(AnaglyphUniversalCamera, _super);
  79734. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79735. var _this = _super.call(this, name, position, scene) || this;
  79736. _this.interaxialDistance = interaxialDistance;
  79737. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79738. return _this;
  79739. }
  79740. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79741. return "AnaglyphUniversalCamera";
  79742. };
  79743. return AnaglyphUniversalCamera;
  79744. }(BABYLON.UniversalCamera));
  79745. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79746. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79747. __extends(StereoscopicFreeCamera, _super);
  79748. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79749. var _this = _super.call(this, name, position, scene) || this;
  79750. _this.interaxialDistance = interaxialDistance;
  79751. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79752. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79753. return _this;
  79754. }
  79755. StereoscopicFreeCamera.prototype.getClassName = function () {
  79756. return "StereoscopicFreeCamera";
  79757. };
  79758. return StereoscopicFreeCamera;
  79759. }(BABYLON.FreeCamera));
  79760. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79761. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79762. __extends(StereoscopicArcRotateCamera, _super);
  79763. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79764. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79765. _this.interaxialDistance = interaxialDistance;
  79766. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79767. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79768. return _this;
  79769. }
  79770. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79771. return "StereoscopicArcRotateCamera";
  79772. };
  79773. return StereoscopicArcRotateCamera;
  79774. }(BABYLON.ArcRotateCamera));
  79775. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79776. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79777. __extends(StereoscopicGamepadCamera, _super);
  79778. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79779. var _this = _super.call(this, name, position, scene) || this;
  79780. _this.interaxialDistance = interaxialDistance;
  79781. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79782. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79783. return _this;
  79784. }
  79785. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79786. return "StereoscopicGamepadCamera";
  79787. };
  79788. return StereoscopicGamepadCamera;
  79789. }(BABYLON.GamepadCamera));
  79790. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79791. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79792. __extends(StereoscopicUniversalCamera, _super);
  79793. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79794. var _this = _super.call(this, name, position, scene) || this;
  79795. _this.interaxialDistance = interaxialDistance;
  79796. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79797. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79798. return _this;
  79799. }
  79800. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79801. return "StereoscopicUniversalCamera";
  79802. };
  79803. return StereoscopicUniversalCamera;
  79804. }(BABYLON.UniversalCamera));
  79805. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79806. })(BABYLON || (BABYLON = {}));
  79807. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79808. var BABYLON;
  79809. (function (BABYLON) {
  79810. var VRExperienceHelperGazer = /** @class */ (function () {
  79811. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  79812. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  79813. this.scene = scene;
  79814. this._pointerDownOnMeshAsked = false;
  79815. this._isActionableMesh = false;
  79816. this._teleportationRequestInitiated = false;
  79817. this._teleportationBackRequestInitiated = false;
  79818. this._dpadPressed = true;
  79819. this._activePointer = false;
  79820. this._id = VRExperienceHelperGazer._idCounter++;
  79821. // Gaze tracker
  79822. if (!gazeTrackerToClone) {
  79823. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  79824. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79825. this._gazeTracker.isPickable = false;
  79826. this._gazeTracker.isVisible = false;
  79827. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  79828. targetMat.specularColor = BABYLON.Color3.Black();
  79829. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79830. targetMat.backFaceCulling = false;
  79831. this._gazeTracker.material = targetMat;
  79832. }
  79833. else {
  79834. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  79835. }
  79836. }
  79837. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  79838. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  79839. };
  79840. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  79841. this._pointerDownOnMeshAsked = true;
  79842. if (this._currentMeshSelected && this._currentHit) {
  79843. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  79844. }
  79845. };
  79846. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  79847. if (this._currentMeshSelected && this._currentHit) {
  79848. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  79849. }
  79850. this._pointerDownOnMeshAsked = false;
  79851. };
  79852. VRExperienceHelperGazer.prototype._activatePointer = function () {
  79853. this._activePointer = true;
  79854. };
  79855. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  79856. this._activePointer = false;
  79857. };
  79858. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  79859. };
  79860. VRExperienceHelperGazer.prototype.dispose = function () {
  79861. this._interactionsEnabled = false;
  79862. this._teleportationEnabled = false;
  79863. };
  79864. VRExperienceHelperGazer._idCounter = 0;
  79865. return VRExperienceHelperGazer;
  79866. }());
  79867. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  79868. __extends(VRExperienceHelperControllerGazer, _super);
  79869. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  79870. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  79871. _this.webVRController = webVRController;
  79872. // Laser pointer
  79873. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  79874. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  79875. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79876. laserPointerMaterial.alpha = 0.6;
  79877. _this._laserPointer.material = laserPointerMaterial;
  79878. _this._laserPointer.rotation.x = Math.PI / 2;
  79879. _this._laserPointer.position.z = -0.5;
  79880. _this._laserPointer.isVisible = false;
  79881. _this._laserPointer.parent = webVRController.mesh;
  79882. return _this;
  79883. }
  79884. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  79885. return this.webVRController.getForwardRay(length);
  79886. };
  79887. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  79888. _super.prototype._activatePointer.call(this);
  79889. this._laserPointer.isVisible = true;
  79890. };
  79891. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  79892. _super.prototype._deactivatePointer.call(this);
  79893. this._laserPointer.isVisible = false;
  79894. };
  79895. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  79896. this._laserPointer.material.emissiveColor = color;
  79897. };
  79898. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  79899. this._laserPointer.parent = mesh;
  79900. };
  79901. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  79902. this._laserPointer.scaling.y = distance;
  79903. this._laserPointer.position.z = -distance / 2;
  79904. };
  79905. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  79906. _super.prototype.dispose.call(this);
  79907. this._laserPointer.dispose();
  79908. };
  79909. return VRExperienceHelperControllerGazer;
  79910. }(VRExperienceHelperGazer));
  79911. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  79912. __extends(VRExperienceHelperCameraGazer, _super);
  79913. function VRExperienceHelperCameraGazer(getCamera, scene) {
  79914. var _this = _super.call(this, scene) || this;
  79915. _this.getCamera = getCamera;
  79916. return _this;
  79917. }
  79918. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  79919. var camera = this.getCamera();
  79920. if (camera) {
  79921. return camera.getForwardRay(length);
  79922. }
  79923. else {
  79924. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  79925. }
  79926. };
  79927. return VRExperienceHelperCameraGazer;
  79928. }(VRExperienceHelperGazer));
  79929. /**
  79930. * Helps to quickly add VR support to an existing scene.
  79931. * See http://doc.babylonjs.com/how_to/webvr_helper
  79932. */
  79933. var VRExperienceHelper = /** @class */ (function () {
  79934. /**
  79935. * Instantiates a VRExperienceHelper.
  79936. * Helps to quickly add VR support to an existing scene.
  79937. * @param scene The scene the VRExperienceHelper belongs to.
  79938. * @param webVROptions Options to modify the vr experience helper's behavior.
  79939. */
  79940. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79941. if (webVROptions === void 0) { webVROptions = {}; }
  79942. var _this = this;
  79943. this.webVROptions = webVROptions;
  79944. // Can the system support WebVR, even if a headset isn't plugged in?
  79945. this._webVRsupported = false;
  79946. // If WebVR is supported, is a headset plugged in and are we ready to present?
  79947. this._webVRready = false;
  79948. // Are we waiting for the requestPresent callback to complete?
  79949. this._webVRrequesting = false;
  79950. // Are we presenting to the headset right now?
  79951. this._webVRpresenting = false;
  79952. // Are we presenting in the fullscreen fallback?
  79953. this._fullscreenVRpresenting = false;
  79954. /**
  79955. * Observable raised when entering VR.
  79956. */
  79957. this.onEnteringVRObservable = new BABYLON.Observable();
  79958. /**
  79959. * Observable raised when exiting VR.
  79960. */
  79961. this.onExitingVRObservable = new BABYLON.Observable();
  79962. /**
  79963. * Observable raised when controller mesh is loaded.
  79964. */
  79965. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79966. this._useCustomVRButton = false;
  79967. this._teleportationRequested = false;
  79968. this._teleportActive = false;
  79969. this._floorMeshesCollection = [];
  79970. this._rotationAllowed = true;
  79971. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  79972. this._rotationRightAsked = false;
  79973. this._rotationLeftAsked = false;
  79974. this._isDefaultTeleportationTarget = true;
  79975. this._teleportationFillColor = "#444444";
  79976. this._teleportationBorderColor = "#FFFFFF";
  79977. this._rotationAngle = 0;
  79978. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  79979. this._padSensibilityUp = 0.65;
  79980. this._padSensibilityDown = 0.35;
  79981. this.leftController = null;
  79982. this.rightController = null;
  79983. /**
  79984. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  79985. */
  79986. this.onNewMeshSelected = new BABYLON.Observable();
  79987. /**
  79988. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  79989. */
  79990. this.onNewMeshPicked = new BABYLON.Observable();
  79991. /**
  79992. * Observable raised before camera teleportation
  79993. */
  79994. this.onBeforeCameraTeleport = new BABYLON.Observable();
  79995. /**
  79996. * Observable raised after camera teleportation
  79997. */
  79998. this.onAfterCameraTeleport = new BABYLON.Observable();
  79999. /**
  80000. * Observable raised when current selected mesh gets unselected
  80001. */
  80002. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80003. /**
  80004. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80005. */
  80006. this.teleportationEnabled = true;
  80007. this._teleportationInitialized = false;
  80008. this._interactionsEnabled = false;
  80009. this._interactionsRequested = false;
  80010. this._displayGaze = true;
  80011. this._displayLaserPointer = true;
  80012. this._onResize = function () {
  80013. _this.moveButtonToBottomRight();
  80014. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80015. _this.exitVR();
  80016. }
  80017. };
  80018. this._onFullscreenChange = function () {
  80019. if (document.fullscreen !== undefined) {
  80020. _this._fullscreenVRpresenting = document.fullscreen;
  80021. }
  80022. else if (document.mozFullScreen !== undefined) {
  80023. _this._fullscreenVRpresenting = document.mozFullScreen;
  80024. }
  80025. else if (document.webkitIsFullScreen !== undefined) {
  80026. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80027. }
  80028. else if (document.msIsFullScreen !== undefined) {
  80029. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80030. }
  80031. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80032. _this.exitVR();
  80033. if (!_this._useCustomVRButton) {
  80034. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80035. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80036. }
  80037. }
  80038. };
  80039. this.beforeRender = function () {
  80040. if (_this.leftController && _this.leftController._activePointer) {
  80041. _this._castRayAndSelectObject(_this.leftController);
  80042. }
  80043. if (_this.rightController && _this.rightController._activePointer) {
  80044. _this._castRayAndSelectObject(_this.rightController);
  80045. }
  80046. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80047. _this._castRayAndSelectObject(_this._cameraGazer);
  80048. }
  80049. else {
  80050. _this._cameraGazer._gazeTracker.isVisible = false;
  80051. }
  80052. };
  80053. this._onNewGamepadConnected = function (gamepad) {
  80054. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80055. if (gamepad.leftStick) {
  80056. gamepad.onleftstickchanged(function (stickValues) {
  80057. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80058. // Listening to classic/xbox gamepad only if no VR controller is active
  80059. if ((!_this.leftController && !_this.rightController) ||
  80060. ((_this.leftController && !_this.leftController._activePointer) &&
  80061. (_this.rightController && !_this.rightController._activePointer))) {
  80062. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80063. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80064. }
  80065. }
  80066. });
  80067. }
  80068. if (gamepad.rightStick) {
  80069. gamepad.onrightstickchanged(function (stickValues) {
  80070. if (_this._teleportationInitialized) {
  80071. _this._checkRotate(stickValues, _this._cameraGazer);
  80072. }
  80073. });
  80074. }
  80075. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80076. gamepad.onbuttondown(function (buttonPressed) {
  80077. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80078. _this._cameraGazer._selectionPointerDown();
  80079. }
  80080. });
  80081. gamepad.onbuttonup(function (buttonPressed) {
  80082. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80083. _this._cameraGazer._selectionPointerUp();
  80084. }
  80085. });
  80086. }
  80087. }
  80088. else {
  80089. var webVRController = gamepad;
  80090. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80091. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80092. _this.rightController = controller;
  80093. }
  80094. else {
  80095. _this.leftController = controller;
  80096. }
  80097. _this._tryEnableInteractionOnController(controller);
  80098. }
  80099. };
  80100. // 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
  80101. this._tryEnableInteractionOnController = function (controller) {
  80102. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80103. _this._enableInteractionOnController(controller);
  80104. }
  80105. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80106. _this._enableTeleportationOnController(controller);
  80107. }
  80108. };
  80109. this._onNewGamepadDisconnected = function (gamepad) {
  80110. if (gamepad instanceof BABYLON.WebVRController) {
  80111. if (gamepad.hand === "left" && _this.leftController != null) {
  80112. _this.leftController.dispose();
  80113. _this.leftController = null;
  80114. }
  80115. if (gamepad.hand === "right" && _this.rightController != null) {
  80116. _this.rightController.dispose();
  80117. _this.rightController = null;
  80118. }
  80119. }
  80120. };
  80121. this._workingVector = BABYLON.Vector3.Zero();
  80122. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80123. this._workingMatrix = BABYLON.Matrix.Identity();
  80124. this._scene = scene;
  80125. this._canvas = scene.getEngine().getRenderingCanvas();
  80126. // Parse options
  80127. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80128. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80129. }
  80130. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80131. webVROptions.createDeviceOrientationCamera = true;
  80132. }
  80133. if (webVROptions.defaultHeight === undefined) {
  80134. webVROptions.defaultHeight = 1.7;
  80135. }
  80136. if (webVROptions.useCustomVRButton) {
  80137. this._useCustomVRButton = true;
  80138. if (webVROptions.customVRButton) {
  80139. this._btnVR = webVROptions.customVRButton;
  80140. }
  80141. }
  80142. if (webVROptions.rayLength) {
  80143. this._rayLength = webVROptions.rayLength;
  80144. }
  80145. this._defaultHeight = webVROptions.defaultHeight;
  80146. // Set position
  80147. if (this._scene.activeCamera) {
  80148. this._position = this._scene.activeCamera.position.clone();
  80149. }
  80150. else {
  80151. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80152. }
  80153. // Set non-vr camera
  80154. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80155. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80156. // Copy data from existing camera
  80157. if (this._scene.activeCamera) {
  80158. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80159. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80160. // Set rotation from previous camera
  80161. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80162. var targetCamera = this._scene.activeCamera;
  80163. if (targetCamera.rotationQuaternion) {
  80164. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80165. }
  80166. else {
  80167. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80168. }
  80169. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80170. }
  80171. }
  80172. this._scene.activeCamera = this._deviceOrientationCamera;
  80173. if (this._canvas) {
  80174. this._scene.activeCamera.attachControl(this._canvas);
  80175. }
  80176. }
  80177. else {
  80178. this._existingCamera = this._scene.activeCamera;
  80179. }
  80180. // Create VR cameras
  80181. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80182. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80183. }
  80184. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80185. this._webVRCamera.useStandingMatrix();
  80186. // Create default button
  80187. if (!this._useCustomVRButton) {
  80188. this._btnVR = document.createElement("BUTTON");
  80189. this._btnVR.className = "babylonVRicon";
  80190. this._btnVR.id = "babylonVRiconbtn";
  80191. this._btnVR.title = "Click to switch to VR";
  80192. 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) }";
  80193. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80194. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80195. // css += ".babylonVRicon.vrdisplaysupported { }";
  80196. // css += ".babylonVRicon.vrdisplayready { }";
  80197. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80198. var style = document.createElement('style');
  80199. style.appendChild(document.createTextNode(css));
  80200. document.getElementsByTagName('head')[0].appendChild(style);
  80201. this.moveButtonToBottomRight();
  80202. }
  80203. // VR button click event
  80204. if (this._btnVR) {
  80205. this._btnVR.addEventListener("click", function () {
  80206. if (!_this.isInVRMode) {
  80207. _this.enterVR();
  80208. }
  80209. else {
  80210. _this.exitVR();
  80211. }
  80212. });
  80213. }
  80214. // Window events
  80215. window.addEventListener("resize", this._onResize);
  80216. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80217. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80218. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80219. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80220. // Display vr button when headset is connected
  80221. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80222. this.displayVRButton();
  80223. }
  80224. else {
  80225. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80226. if (e.vrDisplay) {
  80227. _this.displayVRButton();
  80228. }
  80229. });
  80230. }
  80231. // Exiting VR mode using 'ESC' key on desktop
  80232. this._onKeyDown = function (event) {
  80233. if (event.keyCode === 27 && _this.isInVRMode) {
  80234. _this.exitVR();
  80235. }
  80236. };
  80237. document.addEventListener("keydown", this._onKeyDown);
  80238. // Exiting VR mode double tapping the touch screen
  80239. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80240. if (_this.isInVRMode) {
  80241. _this.exitVR();
  80242. if (_this._fullscreenVRpresenting) {
  80243. _this._scene.getEngine().switchFullscreen(true);
  80244. }
  80245. }
  80246. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80247. // Listen for WebVR display changes
  80248. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80249. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80250. this._onVRRequestPresentStart = function () {
  80251. _this._webVRrequesting = true;
  80252. _this.updateButtonVisibility();
  80253. };
  80254. this._onVRRequestPresentComplete = function (success) {
  80255. _this._webVRrequesting = false;
  80256. _this.updateButtonVisibility();
  80257. };
  80258. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80259. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80260. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80261. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80262. scene.onDisposeObservable.add(function () {
  80263. _this.dispose();
  80264. });
  80265. // Gamepad connection events
  80266. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80267. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80268. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80269. this.updateButtonVisibility();
  80270. //create easing functions
  80271. this._circleEase = new BABYLON.CircleEase();
  80272. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80273. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80274. }
  80275. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80276. /** Return this.onEnteringVRObservable
  80277. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80278. */
  80279. get: function () {
  80280. return this.onEnteringVRObservable;
  80281. },
  80282. enumerable: true,
  80283. configurable: true
  80284. });
  80285. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80286. /** Return this.onExitingVRObservable
  80287. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80288. */
  80289. get: function () {
  80290. return this.onExitingVRObservable;
  80291. },
  80292. enumerable: true,
  80293. configurable: true
  80294. });
  80295. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80296. /** Return this.onControllerMeshLoadedObservable
  80297. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80298. */
  80299. get: function () {
  80300. return this.onControllerMeshLoadedObservable;
  80301. },
  80302. enumerable: true,
  80303. configurable: true
  80304. });
  80305. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80306. /**
  80307. * The mesh used to display where the user is going to teleport.
  80308. */
  80309. get: function () {
  80310. return this._teleportationTarget;
  80311. },
  80312. /**
  80313. * Sets the mesh to be used to display where the user is going to teleport.
  80314. */
  80315. set: function (value) {
  80316. if (value) {
  80317. value.name = "teleportationTarget";
  80318. this._isDefaultTeleportationTarget = false;
  80319. this._teleportationTarget = value;
  80320. }
  80321. },
  80322. enumerable: true,
  80323. configurable: true
  80324. });
  80325. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80326. /**
  80327. * The mesh used to display where the user is selecting,
  80328. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80329. * See http://doc.babylonjs.com/resources/baking_transformations
  80330. */
  80331. get: function () {
  80332. return this._cameraGazer._gazeTracker;
  80333. },
  80334. set: function (value) {
  80335. if (value) {
  80336. this._cameraGazer._gazeTracker = value;
  80337. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80338. this._cameraGazer._gazeTracker.isPickable = false;
  80339. this._cameraGazer._gazeTracker.isVisible = false;
  80340. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80341. if (this.leftController) {
  80342. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80343. }
  80344. if (this.rightController) {
  80345. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80346. }
  80347. }
  80348. },
  80349. enumerable: true,
  80350. configurable: true
  80351. });
  80352. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80353. /**
  80354. * If the ray of the gaze should be displayed.
  80355. */
  80356. get: function () {
  80357. return this._displayGaze;
  80358. },
  80359. /**
  80360. * Sets if the ray of the gaze should be displayed.
  80361. */
  80362. set: function (value) {
  80363. this._displayGaze = value;
  80364. if (!value) {
  80365. this._cameraGazer._gazeTracker.isVisible = false;
  80366. if (this.leftController) {
  80367. this.leftController._gazeTracker.isVisible = false;
  80368. }
  80369. if (this.rightController) {
  80370. this.rightController._gazeTracker.isVisible = false;
  80371. }
  80372. }
  80373. },
  80374. enumerable: true,
  80375. configurable: true
  80376. });
  80377. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80378. /**
  80379. * If the ray of the LaserPointer should be displayed.
  80380. */
  80381. get: function () {
  80382. return this._displayLaserPointer;
  80383. },
  80384. /**
  80385. * Sets if the ray of the LaserPointer should be displayed.
  80386. */
  80387. set: function (value) {
  80388. this._displayLaserPointer = value;
  80389. if (!value) {
  80390. if (this.rightController) {
  80391. this.rightController._deactivatePointer();
  80392. this.rightController._gazeTracker.isVisible = false;
  80393. }
  80394. if (this.leftController) {
  80395. this.leftController._deactivatePointer();
  80396. this.leftController._gazeTracker.isVisible = false;
  80397. }
  80398. }
  80399. else {
  80400. if (this.rightController) {
  80401. this.rightController._activatePointer();
  80402. }
  80403. else if (this.leftController) {
  80404. this.leftController._activatePointer();
  80405. }
  80406. }
  80407. },
  80408. enumerable: true,
  80409. configurable: true
  80410. });
  80411. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80412. /**
  80413. * The deviceOrientationCamera used as the camera when not in VR.
  80414. */
  80415. get: function () {
  80416. return this._deviceOrientationCamera;
  80417. },
  80418. enumerable: true,
  80419. configurable: true
  80420. });
  80421. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80422. /**
  80423. * Based on the current WebVR support, returns the current VR camera used.
  80424. */
  80425. get: function () {
  80426. if (this._webVRready) {
  80427. return this._webVRCamera;
  80428. }
  80429. else {
  80430. return this._scene.activeCamera;
  80431. }
  80432. },
  80433. enumerable: true,
  80434. configurable: true
  80435. });
  80436. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80437. /**
  80438. * The webVRCamera which is used when in VR.
  80439. */
  80440. get: function () {
  80441. return this._webVRCamera;
  80442. },
  80443. enumerable: true,
  80444. configurable: true
  80445. });
  80446. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80447. /**
  80448. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80449. */
  80450. get: function () {
  80451. return this._vrDeviceOrientationCamera;
  80452. },
  80453. enumerable: true,
  80454. configurable: true
  80455. });
  80456. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80457. get: function () {
  80458. var result = this._cameraGazer._teleportationRequestInitiated
  80459. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80460. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80461. return result;
  80462. },
  80463. enumerable: true,
  80464. configurable: true
  80465. });
  80466. // Raised when one of the controller has loaded successfully its associated default mesh
  80467. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80468. if (this.leftController && this.leftController.webVRController == webVRController) {
  80469. this._tryEnableInteractionOnController(this.leftController);
  80470. }
  80471. if (this.rightController && this.rightController.webVRController == webVRController) {
  80472. this._tryEnableInteractionOnController(this.rightController);
  80473. }
  80474. try {
  80475. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80476. }
  80477. catch (err) {
  80478. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80479. }
  80480. };
  80481. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80482. /**
  80483. * Gets a value indicating if we are currently in VR mode.
  80484. */
  80485. get: function () {
  80486. return this._webVRpresenting || this._fullscreenVRpresenting;
  80487. },
  80488. enumerable: true,
  80489. configurable: true
  80490. });
  80491. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80492. var vrDisplay = this._scene.getEngine().getVRDevice();
  80493. if (vrDisplay) {
  80494. var wasPresenting = this._webVRpresenting;
  80495. // A VR display is connected
  80496. this._webVRpresenting = vrDisplay.isPresenting;
  80497. if (wasPresenting && !this._webVRpresenting)
  80498. this.exitVR();
  80499. }
  80500. else {
  80501. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80502. }
  80503. this.updateButtonVisibility();
  80504. };
  80505. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80506. this._webVRsupported = eventArgs.vrSupported;
  80507. this._webVRready = !!eventArgs.vrDisplay;
  80508. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80509. this.updateButtonVisibility();
  80510. };
  80511. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80512. if (this._canvas && !this._useCustomVRButton) {
  80513. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80514. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80515. }
  80516. };
  80517. VRExperienceHelper.prototype.displayVRButton = function () {
  80518. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80519. document.body.appendChild(this._btnVR);
  80520. this._btnVRDisplayed = true;
  80521. }
  80522. };
  80523. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80524. if (!this._btnVR || this._useCustomVRButton) {
  80525. return;
  80526. }
  80527. this._btnVR.className = "babylonVRicon";
  80528. if (this.isInVRMode) {
  80529. this._btnVR.className += " vrdisplaypresenting";
  80530. }
  80531. else {
  80532. if (this._webVRready)
  80533. this._btnVR.className += " vrdisplayready";
  80534. if (this._webVRsupported)
  80535. this._btnVR.className += " vrdisplaysupported";
  80536. if (this._webVRrequesting)
  80537. this._btnVR.className += " vrdisplayrequesting";
  80538. }
  80539. };
  80540. /**
  80541. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80542. * Otherwise, will use the fullscreen API.
  80543. */
  80544. VRExperienceHelper.prototype.enterVR = function () {
  80545. if (this.onEnteringVRObservable) {
  80546. try {
  80547. this.onEnteringVRObservable.notifyObservers(this);
  80548. }
  80549. catch (err) {
  80550. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80551. }
  80552. }
  80553. if (this._scene.activeCamera) {
  80554. this._position = this._scene.activeCamera.position.clone();
  80555. // make sure that we return to the last active camera
  80556. this._existingCamera = this._scene.activeCamera;
  80557. }
  80558. if (this._webVRrequesting)
  80559. return;
  80560. // If WebVR is supported and a headset is connected
  80561. if (this._webVRready) {
  80562. if (!this._webVRpresenting) {
  80563. this._webVRCamera.position = this._position;
  80564. this._scene.activeCamera = this._webVRCamera;
  80565. }
  80566. }
  80567. else if (this._vrDeviceOrientationCamera) {
  80568. this._vrDeviceOrientationCamera.position = this._position;
  80569. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80570. this._scene.getEngine().switchFullscreen(true);
  80571. this.updateButtonVisibility();
  80572. }
  80573. if (this._scene.activeCamera && this._canvas) {
  80574. this._scene.activeCamera.attachControl(this._canvas);
  80575. }
  80576. if (this._interactionsEnabled) {
  80577. this._scene.registerBeforeRender(this.beforeRender);
  80578. }
  80579. };
  80580. /**
  80581. * Attempt to exit VR, or fullscreen.
  80582. */
  80583. VRExperienceHelper.prototype.exitVR = function () {
  80584. if (this.onExitingVRObservable) {
  80585. try {
  80586. this.onExitingVRObservable.notifyObservers(this);
  80587. }
  80588. catch (err) {
  80589. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80590. }
  80591. }
  80592. if (this._webVRpresenting) {
  80593. this._scene.getEngine().disableVR();
  80594. }
  80595. if (this._scene.activeCamera) {
  80596. this._position = this._scene.activeCamera.position.clone();
  80597. }
  80598. if (this._deviceOrientationCamera) {
  80599. this._deviceOrientationCamera.position = this._position;
  80600. this._scene.activeCamera = this._deviceOrientationCamera;
  80601. if (this._canvas) {
  80602. this._scene.activeCamera.attachControl(this._canvas);
  80603. }
  80604. }
  80605. else if (this._existingCamera) {
  80606. this._existingCamera.position = this._position;
  80607. this._scene.activeCamera = this._existingCamera;
  80608. }
  80609. this.updateButtonVisibility();
  80610. if (this._interactionsEnabled) {
  80611. this._scene.unregisterBeforeRender(this.beforeRender);
  80612. }
  80613. };
  80614. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80615. /**
  80616. * The position of the vr experience helper.
  80617. */
  80618. get: function () {
  80619. return this._position;
  80620. },
  80621. /**
  80622. * Sets the position of the vr experience helper.
  80623. */
  80624. set: function (value) {
  80625. this._position = value;
  80626. if (this._scene.activeCamera) {
  80627. this._scene.activeCamera.position = value;
  80628. }
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. /**
  80634. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80635. */
  80636. VRExperienceHelper.prototype.enableInteractions = function () {
  80637. var _this = this;
  80638. if (!this._interactionsEnabled) {
  80639. this._interactionsRequested = true;
  80640. if (this.leftController) {
  80641. this._enableInteractionOnController(this.leftController);
  80642. }
  80643. if (this.rightController) {
  80644. this._enableInteractionOnController(this.rightController);
  80645. }
  80646. this.raySelectionPredicate = function (mesh) {
  80647. return mesh.isVisible;
  80648. };
  80649. this.meshSelectionPredicate = function (mesh) {
  80650. return true;
  80651. };
  80652. this._raySelectionPredicate = function (mesh) {
  80653. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80654. && mesh.name.indexOf("teleportationTarget") === -1
  80655. && mesh.name.indexOf("torusTeleportation") === -1
  80656. && mesh.name.indexOf("laserPointer") === -1)) {
  80657. return _this.raySelectionPredicate(mesh);
  80658. }
  80659. return false;
  80660. };
  80661. this._interactionsEnabled = true;
  80662. }
  80663. };
  80664. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80665. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80666. if (this._floorMeshesCollection[i].id === mesh.id) {
  80667. return true;
  80668. }
  80669. }
  80670. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80671. return true;
  80672. }
  80673. return false;
  80674. };
  80675. /**
  80676. * Adds a floor mesh to be used for teleportation.
  80677. * @param floorMesh the mesh to be used for teleportation.
  80678. */
  80679. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80680. if (!this._floorMeshesCollection) {
  80681. return;
  80682. }
  80683. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80684. return;
  80685. }
  80686. this._floorMeshesCollection.push(floorMesh);
  80687. };
  80688. /**
  80689. * Removes a floor mesh from being used for teleportation.
  80690. * @param floorMesh the mesh to be removed.
  80691. */
  80692. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80693. if (!this._floorMeshesCollection) {
  80694. return;
  80695. }
  80696. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80697. if (meshIndex !== -1) {
  80698. this._floorMeshesCollection.splice(meshIndex, 1);
  80699. }
  80700. };
  80701. /**
  80702. * Enables interactions and teleportation using the VR controllers and gaze.
  80703. * @param vrTeleportationOptions options to modify teleportation behavior.
  80704. */
  80705. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80706. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80707. if (!this._teleportationInitialized) {
  80708. this._teleportationRequested = true;
  80709. this.enableInteractions();
  80710. if (vrTeleportationOptions.floorMeshName) {
  80711. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80712. }
  80713. if (vrTeleportationOptions.floorMeshes) {
  80714. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80715. }
  80716. if (this.leftController != null) {
  80717. this._enableTeleportationOnController(this.leftController);
  80718. }
  80719. if (this.rightController != null) {
  80720. this._enableTeleportationOnController(this.rightController);
  80721. }
  80722. // Creates an image processing post process for the vignette not relying
  80723. // on the main scene configuration for image processing to reduce setup and spaces
  80724. // (gamma/linear) conflicts.
  80725. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80726. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80727. imageProcessingConfiguration.vignetteEnabled = true;
  80728. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80729. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80730. this._teleportationInitialized = true;
  80731. if (this._isDefaultTeleportationTarget) {
  80732. this._createTeleportationCircles();
  80733. }
  80734. }
  80735. };
  80736. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  80737. var _this = this;
  80738. var controllerMesh = controller.webVRController.mesh;
  80739. if (controllerMesh) {
  80740. var makeNotPick = function (root) {
  80741. root.name += " laserPointer";
  80742. root.getChildMeshes().forEach(function (c) {
  80743. makeNotPick(c);
  80744. });
  80745. };
  80746. makeNotPick(controllerMesh);
  80747. var childMeshes = controllerMesh.getChildMeshes();
  80748. for (var i = 0; i < childMeshes.length; i++) {
  80749. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80750. controllerMesh = childMeshes[i];
  80751. break;
  80752. }
  80753. }
  80754. controller._setLaserPointerParent(controllerMesh);
  80755. controller._interactionsEnabled = true;
  80756. controller._activatePointer();
  80757. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80758. // Enabling / disabling laserPointer
  80759. if (_this._displayLaserPointer && stateObject.value === 1) {
  80760. if (controller._activePointer) {
  80761. controller._deactivatePointer();
  80762. }
  80763. else {
  80764. controller._activatePointer();
  80765. }
  80766. if (_this.displayGaze) {
  80767. controller._gazeTracker.isVisible = controller._activePointer;
  80768. }
  80769. }
  80770. });
  80771. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80772. if (!controller._pointerDownOnMeshAsked) {
  80773. if (stateObject.value > _this._padSensibilityUp) {
  80774. controller._selectionPointerDown();
  80775. }
  80776. }
  80777. else if (stateObject.value < _this._padSensibilityDown) {
  80778. controller._selectionPointerUp();
  80779. }
  80780. });
  80781. }
  80782. };
  80783. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  80784. // Dont teleport if another gaze already requested teleportation
  80785. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  80786. return;
  80787. }
  80788. if (!gazer._teleportationRequestInitiated) {
  80789. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  80790. gazer._activatePointer();
  80791. gazer._teleportationRequestInitiated = true;
  80792. }
  80793. }
  80794. else {
  80795. // Listening to the proper controller values changes to confirm teleportation
  80796. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80797. if (this._teleportActive) {
  80798. this._teleportCamera(this._haloCenter);
  80799. }
  80800. gazer._teleportationRequestInitiated = false;
  80801. }
  80802. }
  80803. };
  80804. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  80805. // Only rotate when user is not currently selecting a teleportation location
  80806. if (gazer._teleportationRequestInitiated) {
  80807. return;
  80808. }
  80809. if (!this._rotationLeftAsked) {
  80810. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  80811. this._rotationLeftAsked = true;
  80812. if (this._rotationAllowed) {
  80813. this._rotateCamera(false);
  80814. }
  80815. }
  80816. }
  80817. else {
  80818. if (stateObject.x > -this._padSensibilityDown) {
  80819. this._rotationLeftAsked = false;
  80820. }
  80821. }
  80822. if (!this._rotationRightAsked) {
  80823. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  80824. this._rotationRightAsked = true;
  80825. if (this._rotationAllowed) {
  80826. this._rotateCamera(true);
  80827. }
  80828. }
  80829. }
  80830. else {
  80831. if (stateObject.x < this._padSensibilityDown) {
  80832. this._rotationRightAsked = false;
  80833. }
  80834. }
  80835. };
  80836. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  80837. // Only teleport backwards when user is not currently selecting a teleportation location
  80838. if (gazer._teleportationRequestInitiated) {
  80839. return;
  80840. }
  80841. // Teleport backwards
  80842. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  80843. if (!gazer._teleportationBackRequestInitiated) {
  80844. if (!this.currentVRCamera) {
  80845. return;
  80846. }
  80847. // Get rotation and position of the current camera
  80848. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80849. var position = this.currentVRCamera.position;
  80850. // If the camera has device position, use that instead
  80851. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80852. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80853. position = this.currentVRCamera.devicePosition;
  80854. }
  80855. // Get matrix with only the y rotation of the device rotation
  80856. rotation.toEulerAnglesToRef(this._workingVector);
  80857. this._workingVector.z = 0;
  80858. this._workingVector.x = 0;
  80859. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80860. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80861. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80862. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80863. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80864. var ray = new BABYLON.Ray(position, this._workingVector);
  80865. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80866. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80867. this._teleportCamera(hit.pickedPoint);
  80868. }
  80869. gazer._teleportationBackRequestInitiated = true;
  80870. }
  80871. }
  80872. else {
  80873. gazer._teleportationBackRequestInitiated = false;
  80874. }
  80875. };
  80876. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  80877. var _this = this;
  80878. var controllerMesh = controller.webVRController.mesh;
  80879. if (controllerMesh) {
  80880. if (!controller._interactionsEnabled) {
  80881. this._enableInteractionOnController(controller);
  80882. }
  80883. controller._interactionsEnabled = true;
  80884. controller._teleportationEnabled = true;
  80885. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80886. controller._dpadPressed = false;
  80887. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80888. controller._dpadPressed = stateObject.pressed;
  80889. if (!controller._dpadPressed) {
  80890. _this._rotationLeftAsked = false;
  80891. _this._rotationRightAsked = false;
  80892. controller._teleportationBackRequestInitiated = false;
  80893. }
  80894. });
  80895. }
  80896. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80897. if (_this.teleportationEnabled) {
  80898. _this._checkTeleportBackwards(stateObject, controller);
  80899. _this._checkTeleportWithRay(stateObject, controller);
  80900. }
  80901. _this._checkRotate(stateObject, controller);
  80902. });
  80903. }
  80904. };
  80905. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80906. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80907. this._teleportationTarget.isPickable = false;
  80908. var length = 512;
  80909. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80910. dynamicTexture.hasAlpha = true;
  80911. var context = dynamicTexture.getContext();
  80912. var centerX = length / 2;
  80913. var centerY = length / 2;
  80914. var radius = 200;
  80915. context.beginPath();
  80916. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80917. context.fillStyle = this._teleportationFillColor;
  80918. context.fill();
  80919. context.lineWidth = 10;
  80920. context.strokeStyle = this._teleportationBorderColor;
  80921. context.stroke();
  80922. context.closePath();
  80923. dynamicTexture.update();
  80924. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80925. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80926. this._teleportationTarget.material = teleportationCircleMaterial;
  80927. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80928. torus.isPickable = false;
  80929. torus.parent = this._teleportationTarget;
  80930. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80931. var keys = [];
  80932. keys.push({
  80933. frame: 0,
  80934. value: 0
  80935. });
  80936. keys.push({
  80937. frame: 30,
  80938. value: 0.4
  80939. });
  80940. keys.push({
  80941. frame: 60,
  80942. value: 0
  80943. });
  80944. animationInnerCircle.setKeys(keys);
  80945. var easingFunction = new BABYLON.SineEase();
  80946. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80947. animationInnerCircle.setEasingFunction(easingFunction);
  80948. torus.animations = [];
  80949. torus.animations.push(animationInnerCircle);
  80950. this._scene.beginAnimation(torus, 0, 60, true);
  80951. this._hideTeleportationTarget();
  80952. };
  80953. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  80954. this._teleportActive = true;
  80955. if (this._teleportationInitialized) {
  80956. this._teleportationTarget.isVisible = true;
  80957. if (this._isDefaultTeleportationTarget) {
  80958. this._teleportationTarget.getChildren()[0].isVisible = true;
  80959. }
  80960. }
  80961. };
  80962. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  80963. this._teleportActive = false;
  80964. if (this._teleportationInitialized) {
  80965. this._teleportationTarget.isVisible = false;
  80966. if (this._isDefaultTeleportationTarget) {
  80967. this._teleportationTarget.getChildren()[0].isVisible = false;
  80968. }
  80969. }
  80970. };
  80971. VRExperienceHelper.prototype._rotateCamera = function (right) {
  80972. var _this = this;
  80973. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80974. return;
  80975. }
  80976. if (right) {
  80977. this._rotationAngle++;
  80978. }
  80979. else {
  80980. this._rotationAngle--;
  80981. }
  80982. this.currentVRCamera.animations = [];
  80983. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  80984. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80985. var animationRotationKeys = [];
  80986. animationRotationKeys.push({
  80987. frame: 0,
  80988. value: this.currentVRCamera.rotationQuaternion
  80989. });
  80990. animationRotationKeys.push({
  80991. frame: 6,
  80992. value: target
  80993. });
  80994. animationRotation.setKeys(animationRotationKeys);
  80995. animationRotation.setEasingFunction(this._circleEase);
  80996. this.currentVRCamera.animations.push(animationRotation);
  80997. this._postProcessMove.animations = [];
  80998. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80999. var vignetteWeightKeys = [];
  81000. vignetteWeightKeys.push({
  81001. frame: 0,
  81002. value: 0
  81003. });
  81004. vignetteWeightKeys.push({
  81005. frame: 3,
  81006. value: 4
  81007. });
  81008. vignetteWeightKeys.push({
  81009. frame: 6,
  81010. value: 0
  81011. });
  81012. animationPP.setKeys(vignetteWeightKeys);
  81013. animationPP.setEasingFunction(this._circleEase);
  81014. this._postProcessMove.animations.push(animationPP);
  81015. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81016. var vignetteStretchKeys = [];
  81017. vignetteStretchKeys.push({
  81018. frame: 0,
  81019. value: 0
  81020. });
  81021. vignetteStretchKeys.push({
  81022. frame: 3,
  81023. value: 10
  81024. });
  81025. vignetteStretchKeys.push({
  81026. frame: 6,
  81027. value: 0
  81028. });
  81029. animationPP2.setKeys(vignetteStretchKeys);
  81030. animationPP2.setEasingFunction(this._circleEase);
  81031. this._postProcessMove.animations.push(animationPP2);
  81032. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81033. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81034. this._postProcessMove.samples = 4;
  81035. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81036. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81037. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81038. });
  81039. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81040. };
  81041. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81042. if (hit.pickedPoint) {
  81043. if (gazer._teleportationRequestInitiated) {
  81044. this._displayTeleportationTarget();
  81045. this._haloCenter.copyFrom(hit.pickedPoint);
  81046. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81047. }
  81048. var pickNormal = hit.getNormal(true, false);
  81049. if (pickNormal) {
  81050. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81051. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81052. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81053. }
  81054. this._teleportationTarget.position.y += 0.1;
  81055. }
  81056. };
  81057. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81058. var _this = this;
  81059. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81060. return;
  81061. }
  81062. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81063. // offset of the headset from the anchor.
  81064. if (this.webVRCamera.leftCamera) {
  81065. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81066. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81067. location.subtractToRef(this._workingVector, this._workingVector);
  81068. }
  81069. else {
  81070. this._workingVector.copyFrom(location);
  81071. }
  81072. // Add height to account for user's height offset
  81073. if (this.isInVRMode) {
  81074. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81075. }
  81076. else {
  81077. this._workingVector.y += this._defaultHeight;
  81078. }
  81079. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81080. // Create animation from the camera's position to the new location
  81081. this.currentVRCamera.animations = [];
  81082. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81083. var animationCameraTeleportationKeys = [{
  81084. frame: 0,
  81085. value: this.currentVRCamera.position
  81086. },
  81087. {
  81088. frame: 11,
  81089. value: this._workingVector
  81090. }
  81091. ];
  81092. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81093. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81094. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81095. this._postProcessMove.animations = [];
  81096. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81097. var vignetteWeightKeys = [];
  81098. vignetteWeightKeys.push({
  81099. frame: 0,
  81100. value: 0
  81101. });
  81102. vignetteWeightKeys.push({
  81103. frame: 5,
  81104. value: 8
  81105. });
  81106. vignetteWeightKeys.push({
  81107. frame: 11,
  81108. value: 0
  81109. });
  81110. animationPP.setKeys(vignetteWeightKeys);
  81111. this._postProcessMove.animations.push(animationPP);
  81112. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81113. var vignetteStretchKeys = [];
  81114. vignetteStretchKeys.push({
  81115. frame: 0,
  81116. value: 0
  81117. });
  81118. vignetteStretchKeys.push({
  81119. frame: 5,
  81120. value: 10
  81121. });
  81122. vignetteStretchKeys.push({
  81123. frame: 11,
  81124. value: 0
  81125. });
  81126. animationPP2.setKeys(vignetteStretchKeys);
  81127. this._postProcessMove.animations.push(animationPP2);
  81128. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81129. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81130. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81131. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81132. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81133. });
  81134. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81135. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81136. });
  81137. this._hideTeleportationTarget();
  81138. };
  81139. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81140. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81141. return;
  81142. }
  81143. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81144. // Moving the gazeTracker on the mesh face targetted
  81145. if (hit && hit.pickedPoint) {
  81146. if (this._displayGaze) {
  81147. var multiplier = 1;
  81148. gazer._gazeTracker.isVisible = true;
  81149. if (gazer._isActionableMesh) {
  81150. multiplier = 3;
  81151. }
  81152. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81153. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81154. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81155. var pickNormal = hit.getNormal();
  81156. // To avoid z-fighting
  81157. var deltaFighting = 0.002;
  81158. if (pickNormal) {
  81159. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81160. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81161. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81162. }
  81163. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81164. if (gazer._gazeTracker.position.x < 0) {
  81165. gazer._gazeTracker.position.x += deltaFighting;
  81166. }
  81167. else {
  81168. gazer._gazeTracker.position.x -= deltaFighting;
  81169. }
  81170. if (gazer._gazeTracker.position.y < 0) {
  81171. gazer._gazeTracker.position.y += deltaFighting;
  81172. }
  81173. else {
  81174. gazer._gazeTracker.position.y -= deltaFighting;
  81175. }
  81176. if (gazer._gazeTracker.position.z < 0) {
  81177. gazer._gazeTracker.position.z += deltaFighting;
  81178. }
  81179. else {
  81180. gazer._gazeTracker.position.z -= deltaFighting;
  81181. }
  81182. }
  81183. // Changing the size of the laser pointer based on the distance from the targetted point
  81184. gazer._updatePointerDistance(hit.distance);
  81185. }
  81186. else {
  81187. gazer._gazeTracker.isVisible = false;
  81188. }
  81189. if (hit && hit.pickedMesh) {
  81190. gazer._currentHit = hit;
  81191. if (gazer._pointerDownOnMeshAsked) {
  81192. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81193. }
  81194. // The object selected is the floor, we're in a teleportation scenario
  81195. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81196. // Moving the teleportation area to this targetted point
  81197. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81198. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81199. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81200. }
  81201. gazer._currentMeshSelected = null;
  81202. if (gazer._teleportationRequestInitiated) {
  81203. this._moveTeleportationSelectorTo(hit, gazer);
  81204. }
  81205. return;
  81206. }
  81207. // If not, we're in a selection scenario
  81208. //this._teleportationAllowed = false;
  81209. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81210. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81211. this.onNewMeshPicked.notifyObservers(hit);
  81212. gazer._currentMeshSelected = hit.pickedMesh;
  81213. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81214. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81215. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81216. gazer._isActionableMesh = true;
  81217. }
  81218. else {
  81219. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81220. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81221. gazer._isActionableMesh = false;
  81222. }
  81223. try {
  81224. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81225. }
  81226. catch (err) {
  81227. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81228. }
  81229. }
  81230. else {
  81231. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81232. gazer._currentMeshSelected = null;
  81233. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81234. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81235. }
  81236. }
  81237. }
  81238. else {
  81239. gazer._currentHit = null;
  81240. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81241. gazer._currentMeshSelected = null;
  81242. //this._teleportationAllowed = false;
  81243. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81244. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81245. }
  81246. };
  81247. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81248. if (mesh) {
  81249. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81250. }
  81251. };
  81252. /**
  81253. * Sets the color of the laser ray from the vr controllers.
  81254. * @param color new color for the ray.
  81255. */
  81256. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81257. if (this.leftController) {
  81258. this.leftController._setLaserPointerColor(color);
  81259. }
  81260. if (this.rightController) {
  81261. this.rightController._setLaserPointerColor(color);
  81262. }
  81263. };
  81264. /**
  81265. * Sets the color of the ray from the vr headsets gaze.
  81266. * @param color new color for the ray.
  81267. */
  81268. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81269. if (!this._cameraGazer._gazeTracker.material) {
  81270. return;
  81271. }
  81272. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81273. if (this.leftController) {
  81274. this.leftController._gazeTracker.material.emissiveColor = color;
  81275. }
  81276. if (this.rightController) {
  81277. this.rightController._gazeTracker.material.emissiveColor = color;
  81278. }
  81279. };
  81280. /**
  81281. * Exits VR and disposes of the vr experience helper
  81282. */
  81283. VRExperienceHelper.prototype.dispose = function () {
  81284. if (this.isInVRMode) {
  81285. this.exitVR();
  81286. }
  81287. if (this._postProcessMove) {
  81288. this._postProcessMove.dispose();
  81289. }
  81290. if (this._webVRCamera) {
  81291. this._webVRCamera.dispose();
  81292. }
  81293. if (this._vrDeviceOrientationCamera) {
  81294. this._vrDeviceOrientationCamera.dispose();
  81295. }
  81296. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81297. document.body.removeChild(this._btnVR);
  81298. }
  81299. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81300. this._deviceOrientationCamera.dispose();
  81301. }
  81302. if (this._cameraGazer) {
  81303. this._cameraGazer.dispose();
  81304. }
  81305. if (this.leftController) {
  81306. this.leftController.dispose();
  81307. }
  81308. if (this.rightController) {
  81309. this.rightController.dispose();
  81310. }
  81311. if (this._teleportationTarget) {
  81312. this._teleportationTarget.dispose();
  81313. }
  81314. this._floorMeshesCollection = [];
  81315. document.removeEventListener("keydown", this._onKeyDown);
  81316. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81317. window.removeEventListener("resize", this._onResize);
  81318. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81319. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81320. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81321. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81322. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81323. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81324. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81325. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81326. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81327. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81328. this._scene.unregisterBeforeRender(this.beforeRender);
  81329. };
  81330. /**
  81331. * Gets the name of the VRExperienceHelper class
  81332. * @returns "VRExperienceHelper"
  81333. */
  81334. VRExperienceHelper.prototype.getClassName = function () {
  81335. return "VRExperienceHelper";
  81336. };
  81337. return VRExperienceHelper;
  81338. }());
  81339. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81340. })(BABYLON || (BABYLON = {}));
  81341. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81342. // Mainly based on these 2 articles :
  81343. // 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
  81344. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81345. var BABYLON;
  81346. (function (BABYLON) {
  81347. var JoystickAxis;
  81348. (function (JoystickAxis) {
  81349. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81350. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81351. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81352. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81353. var VirtualJoystick = /** @class */ (function () {
  81354. function VirtualJoystick(leftJoystick) {
  81355. var _this = this;
  81356. if (leftJoystick) {
  81357. this._leftJoystick = true;
  81358. }
  81359. else {
  81360. this._leftJoystick = false;
  81361. }
  81362. VirtualJoystick._globalJoystickIndex++;
  81363. // By default left & right arrow keys are moving the X
  81364. // and up & down keys are moving the Y
  81365. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81366. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81367. this.reverseLeftRight = false;
  81368. this.reverseUpDown = false;
  81369. // collections of pointers
  81370. this._touches = new BABYLON.StringDictionary();
  81371. this.deltaPosition = BABYLON.Vector3.Zero();
  81372. this._joystickSensibility = 25;
  81373. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81374. this._onResize = function (evt) {
  81375. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81376. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81377. if (VirtualJoystick.vjCanvas) {
  81378. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81379. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81380. }
  81381. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81382. };
  81383. // injecting a canvas element on top of the canvas 3D game
  81384. if (!VirtualJoystick.vjCanvas) {
  81385. window.addEventListener("resize", this._onResize, false);
  81386. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81387. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81388. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81389. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81390. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81391. VirtualJoystick.vjCanvas.style.width = "100%";
  81392. VirtualJoystick.vjCanvas.style.height = "100%";
  81393. VirtualJoystick.vjCanvas.style.position = "absolute";
  81394. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81395. VirtualJoystick.vjCanvas.style.top = "0px";
  81396. VirtualJoystick.vjCanvas.style.left = "0px";
  81397. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81398. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81399. // Support for jQuery PEP polyfill
  81400. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81401. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81402. if (!context) {
  81403. throw new Error("Unable to create canvas for virtual joystick");
  81404. }
  81405. VirtualJoystick.vjCanvasContext = context;
  81406. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81407. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81408. document.body.appendChild(VirtualJoystick.vjCanvas);
  81409. }
  81410. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81411. this.pressed = false;
  81412. // default joystick color
  81413. this._joystickColor = "cyan";
  81414. this._joystickPointerID = -1;
  81415. // current joystick position
  81416. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81417. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81418. // origin joystick position
  81419. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81420. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81421. this._onPointerDownHandlerRef = function (evt) {
  81422. _this._onPointerDown(evt);
  81423. };
  81424. this._onPointerMoveHandlerRef = function (evt) {
  81425. _this._onPointerMove(evt);
  81426. };
  81427. this._onPointerUpHandlerRef = function (evt) {
  81428. _this._onPointerUp(evt);
  81429. };
  81430. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81431. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81432. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81433. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81434. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81435. evt.preventDefault(); // Disables system menu
  81436. }, false);
  81437. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81438. }
  81439. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81440. this._joystickSensibility = newJoystickSensibility;
  81441. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81442. };
  81443. VirtualJoystick.prototype._onPointerDown = function (e) {
  81444. var positionOnScreenCondition;
  81445. e.preventDefault();
  81446. if (this._leftJoystick === true) {
  81447. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81448. }
  81449. else {
  81450. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81451. }
  81452. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81453. // First contact will be dedicated to the virtual joystick
  81454. this._joystickPointerID = e.pointerId;
  81455. this._joystickPointerStartPos.x = e.clientX;
  81456. this._joystickPointerStartPos.y = e.clientY;
  81457. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81458. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81459. this._deltaJoystickVector.x = 0;
  81460. this._deltaJoystickVector.y = 0;
  81461. this.pressed = true;
  81462. this._touches.add(e.pointerId.toString(), e);
  81463. }
  81464. else {
  81465. // You can only trigger the action buttons with a joystick declared
  81466. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81467. this._action();
  81468. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81469. }
  81470. }
  81471. };
  81472. VirtualJoystick.prototype._onPointerMove = function (e) {
  81473. // If the current pointer is the one associated to the joystick (first touch contact)
  81474. if (this._joystickPointerID == e.pointerId) {
  81475. this._joystickPointerPos.x = e.clientX;
  81476. this._joystickPointerPos.y = e.clientY;
  81477. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81478. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81479. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81480. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81481. switch (this._axisTargetedByLeftAndRight) {
  81482. case JoystickAxis.X:
  81483. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81484. break;
  81485. case JoystickAxis.Y:
  81486. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81487. break;
  81488. case JoystickAxis.Z:
  81489. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81490. break;
  81491. }
  81492. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81493. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81494. switch (this._axisTargetedByUpAndDown) {
  81495. case JoystickAxis.X:
  81496. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81497. break;
  81498. case JoystickAxis.Y:
  81499. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81500. break;
  81501. case JoystickAxis.Z:
  81502. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81503. break;
  81504. }
  81505. }
  81506. else {
  81507. var data = this._touches.get(e.pointerId.toString());
  81508. if (data) {
  81509. data.x = e.clientX;
  81510. data.y = e.clientY;
  81511. }
  81512. }
  81513. };
  81514. VirtualJoystick.prototype._onPointerUp = function (e) {
  81515. if (this._joystickPointerID == e.pointerId) {
  81516. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81517. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81518. this._joystickPointerID = -1;
  81519. this.pressed = false;
  81520. }
  81521. else {
  81522. var touch = this._touches.get(e.pointerId.toString());
  81523. if (touch) {
  81524. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81525. }
  81526. }
  81527. this._deltaJoystickVector.x = 0;
  81528. this._deltaJoystickVector.y = 0;
  81529. this._touches.remove(e.pointerId.toString());
  81530. };
  81531. /**
  81532. * Change the color of the virtual joystick
  81533. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81534. */
  81535. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81536. this._joystickColor = newColor;
  81537. };
  81538. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81539. this._action = action;
  81540. };
  81541. // Define which axis you'd like to control for left & right
  81542. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81543. switch (axis) {
  81544. case JoystickAxis.X:
  81545. case JoystickAxis.Y:
  81546. case JoystickAxis.Z:
  81547. this._axisTargetedByLeftAndRight = axis;
  81548. break;
  81549. default:
  81550. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81551. break;
  81552. }
  81553. };
  81554. // Define which axis you'd like to control for up & down
  81555. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81556. switch (axis) {
  81557. case JoystickAxis.X:
  81558. case JoystickAxis.Y:
  81559. case JoystickAxis.Z:
  81560. this._axisTargetedByUpAndDown = axis;
  81561. break;
  81562. default:
  81563. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81564. break;
  81565. }
  81566. };
  81567. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81568. var _this = this;
  81569. if (this.pressed) {
  81570. this._touches.forEach(function (key, touch) {
  81571. if (touch.pointerId === _this._joystickPointerID) {
  81572. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81573. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81574. VirtualJoystick.vjCanvasContext.beginPath();
  81575. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81576. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81577. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81578. VirtualJoystick.vjCanvasContext.stroke();
  81579. VirtualJoystick.vjCanvasContext.closePath();
  81580. VirtualJoystick.vjCanvasContext.beginPath();
  81581. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81582. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81583. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81584. VirtualJoystick.vjCanvasContext.stroke();
  81585. VirtualJoystick.vjCanvasContext.closePath();
  81586. VirtualJoystick.vjCanvasContext.beginPath();
  81587. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81588. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81589. VirtualJoystick.vjCanvasContext.stroke();
  81590. VirtualJoystick.vjCanvasContext.closePath();
  81591. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81592. }
  81593. else {
  81594. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81595. VirtualJoystick.vjCanvasContext.beginPath();
  81596. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81597. VirtualJoystick.vjCanvasContext.beginPath();
  81598. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81599. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81600. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81601. VirtualJoystick.vjCanvasContext.stroke();
  81602. VirtualJoystick.vjCanvasContext.closePath();
  81603. touch.prevX = touch.x;
  81604. touch.prevY = touch.y;
  81605. }
  81606. ;
  81607. });
  81608. }
  81609. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81610. };
  81611. VirtualJoystick.prototype.releaseCanvas = function () {
  81612. if (VirtualJoystick.vjCanvas) {
  81613. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81614. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81615. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81616. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81617. window.removeEventListener("resize", this._onResize);
  81618. document.body.removeChild(VirtualJoystick.vjCanvas);
  81619. VirtualJoystick.vjCanvas = null;
  81620. }
  81621. };
  81622. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81623. VirtualJoystick._globalJoystickIndex = 0;
  81624. return VirtualJoystick;
  81625. }());
  81626. BABYLON.VirtualJoystick = VirtualJoystick;
  81627. })(BABYLON || (BABYLON = {}));
  81628. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81629. var BABYLON;
  81630. (function (BABYLON) {
  81631. // We're mainly based on the logic defined into the FreeCamera code
  81632. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81633. __extends(VirtualJoysticksCamera, _super);
  81634. function VirtualJoysticksCamera(name, position, scene) {
  81635. var _this = _super.call(this, name, position, scene) || this;
  81636. _this.inputs.addVirtualJoystick();
  81637. return _this;
  81638. }
  81639. VirtualJoysticksCamera.prototype.getClassName = function () {
  81640. return "VirtualJoysticksCamera";
  81641. };
  81642. return VirtualJoysticksCamera;
  81643. }(BABYLON.FreeCamera));
  81644. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81645. })(BABYLON || (BABYLON = {}));
  81646. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81647. var BABYLON;
  81648. (function (BABYLON) {
  81649. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81650. function FreeCameraVirtualJoystickInput() {
  81651. }
  81652. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81653. return this._leftjoystick;
  81654. };
  81655. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81656. return this._rightjoystick;
  81657. };
  81658. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81659. if (this._leftjoystick) {
  81660. var camera = this.camera;
  81661. var speed = camera._computeLocalCameraSpeed() * 50;
  81662. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81663. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81664. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81665. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81666. if (!this._leftjoystick.pressed) {
  81667. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81668. }
  81669. if (!this._rightjoystick.pressed) {
  81670. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81671. }
  81672. }
  81673. };
  81674. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81675. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81676. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81677. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81678. this._leftjoystick.setJoystickSensibility(0.15);
  81679. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81680. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81681. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81682. this._rightjoystick.reverseUpDown = true;
  81683. this._rightjoystick.setJoystickSensibility(0.05);
  81684. this._rightjoystick.setJoystickColor("yellow");
  81685. };
  81686. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81687. this._leftjoystick.releaseCanvas();
  81688. this._rightjoystick.releaseCanvas();
  81689. };
  81690. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81691. return "FreeCameraVirtualJoystickInput";
  81692. };
  81693. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81694. return "virtualJoystick";
  81695. };
  81696. return FreeCameraVirtualJoystickInput;
  81697. }());
  81698. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81699. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81700. })(BABYLON || (BABYLON = {}));
  81701. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81702. var BABYLON;
  81703. (function (BABYLON) {
  81704. var SimplificationSettings = /** @class */ (function () {
  81705. function SimplificationSettings(quality, distance, optimizeMesh) {
  81706. this.quality = quality;
  81707. this.distance = distance;
  81708. this.optimizeMesh = optimizeMesh;
  81709. }
  81710. return SimplificationSettings;
  81711. }());
  81712. BABYLON.SimplificationSettings = SimplificationSettings;
  81713. var SimplificationQueue = /** @class */ (function () {
  81714. function SimplificationQueue() {
  81715. this.running = false;
  81716. this._simplificationArray = [];
  81717. }
  81718. SimplificationQueue.prototype.addTask = function (task) {
  81719. this._simplificationArray.push(task);
  81720. };
  81721. SimplificationQueue.prototype.executeNext = function () {
  81722. var task = this._simplificationArray.pop();
  81723. if (task) {
  81724. this.running = true;
  81725. this.runSimplification(task);
  81726. }
  81727. else {
  81728. this.running = false;
  81729. }
  81730. };
  81731. SimplificationQueue.prototype.runSimplification = function (task) {
  81732. var _this = this;
  81733. if (task.parallelProcessing) {
  81734. //parallel simplifier
  81735. task.settings.forEach(function (setting) {
  81736. var simplifier = _this.getSimplifier(task);
  81737. simplifier.simplify(setting, function (newMesh) {
  81738. task.mesh.addLODLevel(setting.distance, newMesh);
  81739. newMesh.isVisible = true;
  81740. //check if it is the last
  81741. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81742. //all done, run the success callback.
  81743. task.successCallback();
  81744. }
  81745. _this.executeNext();
  81746. });
  81747. });
  81748. }
  81749. else {
  81750. //single simplifier.
  81751. var simplifier = this.getSimplifier(task);
  81752. var runDecimation = function (setting, callback) {
  81753. simplifier.simplify(setting, function (newMesh) {
  81754. task.mesh.addLODLevel(setting.distance, newMesh);
  81755. newMesh.isVisible = true;
  81756. //run the next quality level
  81757. callback();
  81758. });
  81759. };
  81760. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81761. runDecimation(task.settings[loop.index], function () {
  81762. loop.executeNext();
  81763. });
  81764. }, function () {
  81765. //execution ended, run the success callback.
  81766. if (task.successCallback) {
  81767. task.successCallback();
  81768. }
  81769. _this.executeNext();
  81770. });
  81771. }
  81772. };
  81773. SimplificationQueue.prototype.getSimplifier = function (task) {
  81774. switch (task.simplificationType) {
  81775. case SimplificationType.QUADRATIC:
  81776. default:
  81777. return new QuadraticErrorSimplification(task.mesh);
  81778. }
  81779. };
  81780. return SimplificationQueue;
  81781. }());
  81782. BABYLON.SimplificationQueue = SimplificationQueue;
  81783. /**
  81784. * The implemented types of simplification.
  81785. * At the moment only Quadratic Error Decimation is implemented.
  81786. */
  81787. var SimplificationType;
  81788. (function (SimplificationType) {
  81789. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81790. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81791. var DecimationTriangle = /** @class */ (function () {
  81792. function DecimationTriangle(vertices) {
  81793. this.vertices = vertices;
  81794. this.error = new Array(4);
  81795. this.deleted = false;
  81796. this.isDirty = false;
  81797. this.deletePending = false;
  81798. this.borderFactor = 0;
  81799. }
  81800. return DecimationTriangle;
  81801. }());
  81802. BABYLON.DecimationTriangle = DecimationTriangle;
  81803. var DecimationVertex = /** @class */ (function () {
  81804. function DecimationVertex(position, id) {
  81805. this.position = position;
  81806. this.id = id;
  81807. this.isBorder = true;
  81808. this.q = new QuadraticMatrix();
  81809. this.triangleCount = 0;
  81810. this.triangleStart = 0;
  81811. this.originalOffsets = [];
  81812. }
  81813. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81814. this.position.copyFrom(newPosition);
  81815. };
  81816. return DecimationVertex;
  81817. }());
  81818. BABYLON.DecimationVertex = DecimationVertex;
  81819. var QuadraticMatrix = /** @class */ (function () {
  81820. function QuadraticMatrix(data) {
  81821. this.data = new Array(10);
  81822. for (var i = 0; i < 10; ++i) {
  81823. if (data && data[i]) {
  81824. this.data[i] = data[i];
  81825. }
  81826. else {
  81827. this.data[i] = 0;
  81828. }
  81829. }
  81830. }
  81831. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81832. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81833. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81834. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81835. return det;
  81836. };
  81837. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81838. for (var i = 0; i < 10; ++i) {
  81839. this.data[i] += matrix.data[i];
  81840. }
  81841. };
  81842. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81843. for (var i = 0; i < 10; ++i) {
  81844. this.data[i] += data[i];
  81845. }
  81846. };
  81847. QuadraticMatrix.prototype.add = function (matrix) {
  81848. var m = new QuadraticMatrix();
  81849. for (var i = 0; i < 10; ++i) {
  81850. m.data[i] = this.data[i] + matrix.data[i];
  81851. }
  81852. return m;
  81853. };
  81854. QuadraticMatrix.FromData = function (a, b, c, d) {
  81855. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81856. };
  81857. //returning an array to avoid garbage collection
  81858. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81859. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81860. };
  81861. return QuadraticMatrix;
  81862. }());
  81863. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81864. var Reference = /** @class */ (function () {
  81865. function Reference(vertexId, triangleId) {
  81866. this.vertexId = vertexId;
  81867. this.triangleId = triangleId;
  81868. }
  81869. return Reference;
  81870. }());
  81871. BABYLON.Reference = Reference;
  81872. /**
  81873. * An implementation of the Quadratic Error simplification algorithm.
  81874. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81875. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81876. * @author RaananW
  81877. */
  81878. var QuadraticErrorSimplification = /** @class */ (function () {
  81879. function QuadraticErrorSimplification(_mesh) {
  81880. this._mesh = _mesh;
  81881. this.syncIterations = 5000;
  81882. this.aggressiveness = 7;
  81883. this.decimationIterations = 100;
  81884. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81885. }
  81886. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81887. var _this = this;
  81888. this.initDecimatedMesh();
  81889. //iterating through the submeshes array, one after the other.
  81890. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81891. _this.initWithMesh(loop.index, function () {
  81892. _this.runDecimation(settings, loop.index, function () {
  81893. loop.executeNext();
  81894. });
  81895. }, settings.optimizeMesh);
  81896. }, function () {
  81897. setTimeout(function () {
  81898. successCallback(_this._reconstructedMesh);
  81899. }, 0);
  81900. });
  81901. };
  81902. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81903. var _this = this;
  81904. var targetCount = ~~(this.triangles.length * settings.quality);
  81905. var deletedTriangles = 0;
  81906. var triangleCount = this.triangles.length;
  81907. var iterationFunction = function (iteration, callback) {
  81908. setTimeout(function () {
  81909. if (iteration % 5 === 0) {
  81910. _this.updateMesh(iteration === 0);
  81911. }
  81912. for (var i = 0; i < _this.triangles.length; ++i) {
  81913. _this.triangles[i].isDirty = false;
  81914. }
  81915. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81916. var trianglesIterator = function (i) {
  81917. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81918. var t = _this.triangles[tIdx];
  81919. if (!t)
  81920. return;
  81921. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81922. return;
  81923. }
  81924. for (var j = 0; j < 3; ++j) {
  81925. if (t.error[j] < threshold) {
  81926. var deleted0 = [];
  81927. var deleted1 = [];
  81928. var v0 = t.vertices[j];
  81929. var v1 = t.vertices[(j + 1) % 3];
  81930. if (v0.isBorder || v1.isBorder)
  81931. continue;
  81932. var p = BABYLON.Vector3.Zero();
  81933. var n = BABYLON.Vector3.Zero();
  81934. var uv = BABYLON.Vector2.Zero();
  81935. var color = new BABYLON.Color4(0, 0, 0, 1);
  81936. _this.calculateError(v0, v1, p, n, uv, color);
  81937. var delTr = new Array();
  81938. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81939. continue;
  81940. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81941. continue;
  81942. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  81943. continue;
  81944. var uniqueArray = new Array();
  81945. delTr.forEach(function (deletedT) {
  81946. if (uniqueArray.indexOf(deletedT) === -1) {
  81947. deletedT.deletePending = true;
  81948. uniqueArray.push(deletedT);
  81949. }
  81950. });
  81951. if (uniqueArray.length % 2 !== 0) {
  81952. continue;
  81953. }
  81954. v0.q = v1.q.add(v0.q);
  81955. v0.updatePosition(p);
  81956. var tStart = _this.references.length;
  81957. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  81958. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  81959. var tCount = _this.references.length - tStart;
  81960. if (tCount <= v0.triangleCount) {
  81961. if (tCount) {
  81962. for (var c = 0; c < tCount; c++) {
  81963. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  81964. }
  81965. }
  81966. }
  81967. else {
  81968. v0.triangleStart = tStart;
  81969. }
  81970. v0.triangleCount = tCount;
  81971. break;
  81972. }
  81973. }
  81974. };
  81975. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  81976. }, 0);
  81977. };
  81978. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  81979. if (triangleCount - deletedTriangles <= targetCount)
  81980. loop.breakLoop();
  81981. else {
  81982. iterationFunction(loop.index, function () {
  81983. loop.executeNext();
  81984. });
  81985. }
  81986. }, function () {
  81987. setTimeout(function () {
  81988. //reconstruct this part of the mesh
  81989. _this.reconstructMesh(submeshIndex);
  81990. successCallback();
  81991. }, 0);
  81992. });
  81993. };
  81994. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  81995. var _this = this;
  81996. this.vertices = [];
  81997. this.triangles = [];
  81998. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81999. var indices = this._mesh.getIndices();
  82000. var submesh = this._mesh.subMeshes[submeshIndex];
  82001. var findInVertices = function (positionToSearch) {
  82002. if (optimizeMesh) {
  82003. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82004. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82005. return _this.vertices[ii];
  82006. }
  82007. }
  82008. }
  82009. return null;
  82010. };
  82011. var vertexReferences = [];
  82012. var vertexInit = function (i) {
  82013. if (!positionData) {
  82014. return;
  82015. }
  82016. var offset = i + submesh.verticesStart;
  82017. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82018. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82019. vertex.originalOffsets.push(offset);
  82020. if (vertex.id === _this.vertices.length) {
  82021. _this.vertices.push(vertex);
  82022. }
  82023. vertexReferences.push(vertex.id);
  82024. };
  82025. //var totalVertices = mesh.getTotalVertices();
  82026. var totalVertices = submesh.verticesCount;
  82027. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82028. var indicesInit = function (i) {
  82029. if (!indices) {
  82030. return;
  82031. }
  82032. var offset = (submesh.indexStart / 3) + i;
  82033. var pos = (offset * 3);
  82034. var i0 = indices[pos + 0];
  82035. var i1 = indices[pos + 1];
  82036. var i2 = indices[pos + 2];
  82037. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82038. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82039. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82040. var triangle = new DecimationTriangle([v0, v1, v2]);
  82041. triangle.originalOffset = pos;
  82042. _this.triangles.push(triangle);
  82043. };
  82044. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82045. _this.init(callback);
  82046. });
  82047. });
  82048. };
  82049. QuadraticErrorSimplification.prototype.init = function (callback) {
  82050. var _this = this;
  82051. var triangleInit1 = function (i) {
  82052. var t = _this.triangles[i];
  82053. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82054. for (var j = 0; j < 3; j++) {
  82055. 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))));
  82056. }
  82057. };
  82058. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82059. var triangleInit2 = function (i) {
  82060. var t = _this.triangles[i];
  82061. for (var j = 0; j < 3; ++j) {
  82062. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82063. }
  82064. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82065. };
  82066. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82067. callback();
  82068. });
  82069. });
  82070. };
  82071. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82072. var newTriangles = [];
  82073. var i;
  82074. for (i = 0; i < this.vertices.length; ++i) {
  82075. this.vertices[i].triangleCount = 0;
  82076. }
  82077. var t;
  82078. var j;
  82079. for (i = 0; i < this.triangles.length; ++i) {
  82080. if (!this.triangles[i].deleted) {
  82081. t = this.triangles[i];
  82082. for (j = 0; j < 3; ++j) {
  82083. t.vertices[j].triangleCount = 1;
  82084. }
  82085. newTriangles.push(t);
  82086. }
  82087. }
  82088. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82089. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82090. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82091. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82092. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82093. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82094. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82095. var vertexCount = 0;
  82096. for (i = 0; i < this.vertices.length; ++i) {
  82097. var vertex = this.vertices[i];
  82098. vertex.id = vertexCount;
  82099. if (vertex.triangleCount) {
  82100. vertex.originalOffsets.forEach(function (originalOffset) {
  82101. if (!normalData) {
  82102. return;
  82103. }
  82104. newPositionData.push(vertex.position.x);
  82105. newPositionData.push(vertex.position.y);
  82106. newPositionData.push(vertex.position.z);
  82107. newNormalData.push(normalData[originalOffset * 3]);
  82108. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82109. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82110. if (uvs && uvs.length) {
  82111. newUVsData.push(uvs[(originalOffset * 2)]);
  82112. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82113. }
  82114. else if (colorsData && colorsData.length) {
  82115. newColorsData.push(colorsData[(originalOffset * 4)]);
  82116. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82117. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82118. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82119. }
  82120. ++vertexCount;
  82121. });
  82122. }
  82123. }
  82124. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82125. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82126. var submeshesArray = this._reconstructedMesh.subMeshes;
  82127. this._reconstructedMesh.subMeshes = [];
  82128. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82129. var originalIndices = this._mesh.getIndices();
  82130. for (i = 0; i < newTriangles.length; ++i) {
  82131. t = newTriangles[i]; //now get the new referencing point for each vertex
  82132. [0, 1, 2].forEach(function (idx) {
  82133. var id = originalIndices[t.originalOffset + idx];
  82134. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82135. if (offset < 0)
  82136. offset = 0;
  82137. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82138. });
  82139. }
  82140. //overwriting the old vertex buffers and indices.
  82141. this._reconstructedMesh.setIndices(newIndicesArray);
  82142. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82143. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82144. if (newUVsData.length > 0)
  82145. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82146. if (newColorsData.length > 0)
  82147. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82148. //create submesh
  82149. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82150. if (submeshIndex > 0) {
  82151. this._reconstructedMesh.subMeshes = [];
  82152. submeshesArray.forEach(function (submesh) {
  82153. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82154. });
  82155. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82156. }
  82157. };
  82158. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82159. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82160. this._reconstructedMesh.material = this._mesh.material;
  82161. this._reconstructedMesh.parent = this._mesh.parent;
  82162. this._reconstructedMesh.isVisible = false;
  82163. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82164. };
  82165. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82166. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82167. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82168. if (t.deleted)
  82169. continue;
  82170. var s = this.references[vertex1.triangleStart + i].vertexId;
  82171. var v1 = t.vertices[(s + 1) % 3];
  82172. var v2 = t.vertices[(s + 2) % 3];
  82173. if ((v1 === vertex2 || v2 === vertex2)) {
  82174. deletedArray[i] = true;
  82175. delTr.push(t);
  82176. continue;
  82177. }
  82178. var d1 = v1.position.subtract(point);
  82179. d1 = d1.normalize();
  82180. var d2 = v2.position.subtract(point);
  82181. d2 = d2.normalize();
  82182. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82183. return true;
  82184. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82185. deletedArray[i] = false;
  82186. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82187. return true;
  82188. }
  82189. return false;
  82190. };
  82191. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82192. var newDeleted = deletedTriangles;
  82193. for (var i = 0; i < vertex.triangleCount; ++i) {
  82194. var ref = this.references[vertex.triangleStart + i];
  82195. var t = this.triangles[ref.triangleId];
  82196. if (t.deleted)
  82197. continue;
  82198. if (deletedArray[i] && t.deletePending) {
  82199. t.deleted = true;
  82200. newDeleted++;
  82201. continue;
  82202. }
  82203. t.vertices[ref.vertexId] = origVertex;
  82204. t.isDirty = true;
  82205. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82206. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82207. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82208. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82209. this.references.push(ref);
  82210. }
  82211. return newDeleted;
  82212. };
  82213. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82214. for (var i = 0; i < this.vertices.length; ++i) {
  82215. var vCount = [];
  82216. var vId = [];
  82217. var v = this.vertices[i];
  82218. var j;
  82219. for (j = 0; j < v.triangleCount; ++j) {
  82220. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82221. for (var ii = 0; ii < 3; ii++) {
  82222. var ofs = 0;
  82223. var vv = triangle.vertices[ii];
  82224. while (ofs < vCount.length) {
  82225. if (vId[ofs] === vv.id)
  82226. break;
  82227. ++ofs;
  82228. }
  82229. if (ofs === vCount.length) {
  82230. vCount.push(1);
  82231. vId.push(vv.id);
  82232. }
  82233. else {
  82234. vCount[ofs]++;
  82235. }
  82236. }
  82237. }
  82238. for (j = 0; j < vCount.length; ++j) {
  82239. if (vCount[j] === 1) {
  82240. this.vertices[vId[j]].isBorder = true;
  82241. }
  82242. else {
  82243. this.vertices[vId[j]].isBorder = false;
  82244. }
  82245. }
  82246. }
  82247. };
  82248. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82249. if (identifyBorders === void 0) { identifyBorders = false; }
  82250. var i;
  82251. if (!identifyBorders) {
  82252. var newTrianglesVector = [];
  82253. for (i = 0; i < this.triangles.length; ++i) {
  82254. if (!this.triangles[i].deleted) {
  82255. newTrianglesVector.push(this.triangles[i]);
  82256. }
  82257. }
  82258. this.triangles = newTrianglesVector;
  82259. }
  82260. for (i = 0; i < this.vertices.length; ++i) {
  82261. this.vertices[i].triangleCount = 0;
  82262. this.vertices[i].triangleStart = 0;
  82263. }
  82264. var t;
  82265. var j;
  82266. var v;
  82267. for (i = 0; i < this.triangles.length; ++i) {
  82268. t = this.triangles[i];
  82269. for (j = 0; j < 3; ++j) {
  82270. v = t.vertices[j];
  82271. v.triangleCount++;
  82272. }
  82273. }
  82274. var tStart = 0;
  82275. for (i = 0; i < this.vertices.length; ++i) {
  82276. this.vertices[i].triangleStart = tStart;
  82277. tStart += this.vertices[i].triangleCount;
  82278. this.vertices[i].triangleCount = 0;
  82279. }
  82280. var newReferences = new Array(this.triangles.length * 3);
  82281. for (i = 0; i < this.triangles.length; ++i) {
  82282. t = this.triangles[i];
  82283. for (j = 0; j < 3; ++j) {
  82284. v = t.vertices[j];
  82285. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82286. v.triangleCount++;
  82287. }
  82288. }
  82289. this.references = newReferences;
  82290. if (identifyBorders) {
  82291. this.identifyBorder();
  82292. }
  82293. };
  82294. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82295. var x = point.x;
  82296. var y = point.y;
  82297. var z = point.z;
  82298. 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
  82299. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82300. };
  82301. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82302. var q = vertex1.q.add(vertex2.q);
  82303. var border = vertex1.isBorder && vertex2.isBorder;
  82304. var error = 0;
  82305. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82306. if (qDet !== 0 && !border) {
  82307. if (!pointResult) {
  82308. pointResult = BABYLON.Vector3.Zero();
  82309. }
  82310. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82311. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82312. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82313. error = this.vertexError(q, pointResult);
  82314. }
  82315. else {
  82316. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82317. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82318. var error1 = this.vertexError(q, vertex1.position);
  82319. var error2 = this.vertexError(q, vertex2.position);
  82320. var error3 = this.vertexError(q, p3);
  82321. error = Math.min(error1, error2, error3);
  82322. if (error === error1) {
  82323. if (pointResult) {
  82324. pointResult.copyFrom(vertex1.position);
  82325. }
  82326. }
  82327. else if (error === error2) {
  82328. if (pointResult) {
  82329. pointResult.copyFrom(vertex2.position);
  82330. }
  82331. }
  82332. else {
  82333. if (pointResult) {
  82334. pointResult.copyFrom(p3);
  82335. }
  82336. }
  82337. }
  82338. return error;
  82339. };
  82340. return QuadraticErrorSimplification;
  82341. }());
  82342. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82343. })(BABYLON || (BABYLON = {}));
  82344. //# sourceMappingURL=babylon.meshSimplification.js.map
  82345. var BABYLON;
  82346. (function (BABYLON) {
  82347. var MeshLODLevel = /** @class */ (function () {
  82348. function MeshLODLevel(distance, mesh) {
  82349. this.distance = distance;
  82350. this.mesh = mesh;
  82351. }
  82352. return MeshLODLevel;
  82353. }());
  82354. BABYLON.MeshLODLevel = MeshLODLevel;
  82355. })(BABYLON || (BABYLON = {}));
  82356. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82357. var BABYLON;
  82358. (function (BABYLON) {
  82359. /**
  82360. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82361. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82362. */
  82363. var SceneOptimization = /** @class */ (function () {
  82364. /**
  82365. * Creates the SceneOptimization object
  82366. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82367. * @param desc defines the description associated with the optimization
  82368. */
  82369. function SceneOptimization(
  82370. /**
  82371. * Defines the priority of this optimization (0 by default which means first in the list)
  82372. */
  82373. priority) {
  82374. if (priority === void 0) { priority = 0; }
  82375. this.priority = priority;
  82376. }
  82377. /**
  82378. * Gets a string describing the action executed by the current optimization
  82379. * @returns description string
  82380. */
  82381. SceneOptimization.prototype.getDescription = function () {
  82382. return "";
  82383. };
  82384. /**
  82385. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82386. * @param scene defines the current scene where to apply this optimization
  82387. * @param optimizer defines the current optimizer
  82388. * @returns true if everything that can be done was applied
  82389. */
  82390. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82391. return true;
  82392. };
  82393. ;
  82394. return SceneOptimization;
  82395. }());
  82396. BABYLON.SceneOptimization = SceneOptimization;
  82397. /**
  82398. * Defines an optimization used to reduce the size of render target textures
  82399. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82400. */
  82401. var TextureOptimization = /** @class */ (function (_super) {
  82402. __extends(TextureOptimization, _super);
  82403. /**
  82404. * Creates the TextureOptimization object
  82405. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82406. * @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
  82407. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82408. */
  82409. function TextureOptimization(
  82410. /**
  82411. * Defines the priority of this optimization (0 by default which means first in the list)
  82412. */
  82413. priority,
  82414. /**
  82415. * 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
  82416. */
  82417. maximumSize,
  82418. /**
  82419. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82420. */
  82421. step) {
  82422. if (priority === void 0) { priority = 0; }
  82423. if (maximumSize === void 0) { maximumSize = 1024; }
  82424. if (step === void 0) { step = 0.5; }
  82425. var _this = _super.call(this, priority) || this;
  82426. _this.priority = priority;
  82427. _this.maximumSize = maximumSize;
  82428. _this.step = step;
  82429. return _this;
  82430. }
  82431. /**
  82432. * Gets a string describing the action executed by the current optimization
  82433. * @returns description string
  82434. */
  82435. TextureOptimization.prototype.getDescription = function () {
  82436. return "Reducing render target texture size to " + this.maximumSize;
  82437. };
  82438. /**
  82439. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82440. * @param scene defines the current scene where to apply this optimization
  82441. * @param optimizer defines the current optimizer
  82442. * @returns true if everything that can be done was applied
  82443. */
  82444. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82445. var allDone = true;
  82446. for (var index = 0; index < scene.textures.length; index++) {
  82447. var texture = scene.textures[index];
  82448. if (!texture.canRescale || texture.getContext) {
  82449. continue;
  82450. }
  82451. var currentSize = texture.getSize();
  82452. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82453. if (maxDimension > this.maximumSize) {
  82454. texture.scale(this.step);
  82455. allDone = false;
  82456. }
  82457. }
  82458. return allDone;
  82459. };
  82460. return TextureOptimization;
  82461. }(SceneOptimization));
  82462. BABYLON.TextureOptimization = TextureOptimization;
  82463. /**
  82464. * Defines an optimization used to increase or decrease the rendering resolution
  82465. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82466. */
  82467. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82468. __extends(HardwareScalingOptimization, _super);
  82469. /**
  82470. * Creates the HardwareScalingOptimization object
  82471. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82472. * @param maximumScale defines the maximum scale to use (2 by default)
  82473. * @param step defines the step to use between two passes (0.5 by default)
  82474. */
  82475. function HardwareScalingOptimization(
  82476. /**
  82477. * Defines the priority of this optimization (0 by default which means first in the list)
  82478. */
  82479. priority,
  82480. /**
  82481. * Defines the maximum scale to use (2 by default)
  82482. */
  82483. maximumScale,
  82484. /**
  82485. * Defines the step to use between two passes (0.5 by default)
  82486. */
  82487. step) {
  82488. if (priority === void 0) { priority = 0; }
  82489. if (maximumScale === void 0) { maximumScale = 2; }
  82490. if (step === void 0) { step = 0.25; }
  82491. var _this = _super.call(this, priority) || this;
  82492. _this.priority = priority;
  82493. _this.maximumScale = maximumScale;
  82494. _this.step = step;
  82495. _this._currentScale = -1;
  82496. _this._directionOffset = 1;
  82497. return _this;
  82498. }
  82499. /**
  82500. * Gets a string describing the action executed by the current optimization
  82501. * @return description string
  82502. */
  82503. HardwareScalingOptimization.prototype.getDescription = function () {
  82504. return "Setting hardware scaling level to " + this._currentScale;
  82505. };
  82506. /**
  82507. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82508. * @param scene defines the current scene where to apply this optimization
  82509. * @param optimizer defines the current optimizer
  82510. * @returns true if everything that can be done was applied
  82511. */
  82512. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82513. if (this._currentScale === -1) {
  82514. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82515. if (this._currentScale > this.maximumScale) {
  82516. this._directionOffset = -1;
  82517. }
  82518. }
  82519. this._currentScale += this._directionOffset * this.step;
  82520. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82521. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82522. };
  82523. ;
  82524. return HardwareScalingOptimization;
  82525. }(SceneOptimization));
  82526. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82527. /**
  82528. * Defines an optimization used to remove shadows
  82529. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82530. */
  82531. var ShadowsOptimization = /** @class */ (function (_super) {
  82532. __extends(ShadowsOptimization, _super);
  82533. function ShadowsOptimization() {
  82534. return _super !== null && _super.apply(this, arguments) || this;
  82535. }
  82536. /**
  82537. * Gets a string describing the action executed by the current optimization
  82538. * @return description string
  82539. */
  82540. ShadowsOptimization.prototype.getDescription = function () {
  82541. return "Turning shadows on/off";
  82542. };
  82543. /**
  82544. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82545. * @param scene defines the current scene where to apply this optimization
  82546. * @param optimizer defines the current optimizer
  82547. * @returns true if everything that can be done was applied
  82548. */
  82549. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82550. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82551. return true;
  82552. };
  82553. ;
  82554. return ShadowsOptimization;
  82555. }(SceneOptimization));
  82556. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82557. /**
  82558. * Defines an optimization used to turn post-processes off
  82559. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82560. */
  82561. var PostProcessesOptimization = /** @class */ (function (_super) {
  82562. __extends(PostProcessesOptimization, _super);
  82563. function PostProcessesOptimization() {
  82564. return _super !== null && _super.apply(this, arguments) || this;
  82565. }
  82566. /**
  82567. * Gets a string describing the action executed by the current optimization
  82568. * @return description string
  82569. */
  82570. PostProcessesOptimization.prototype.getDescription = function () {
  82571. return "Turning post-processes on/off";
  82572. };
  82573. /**
  82574. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82575. * @param scene defines the current scene where to apply this optimization
  82576. * @param optimizer defines the current optimizer
  82577. * @returns true if everything that can be done was applied
  82578. */
  82579. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82580. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82581. return true;
  82582. };
  82583. ;
  82584. return PostProcessesOptimization;
  82585. }(SceneOptimization));
  82586. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82587. /**
  82588. * Defines an optimization used to turn lens flares off
  82589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82590. */
  82591. var LensFlaresOptimization = /** @class */ (function (_super) {
  82592. __extends(LensFlaresOptimization, _super);
  82593. function LensFlaresOptimization() {
  82594. return _super !== null && _super.apply(this, arguments) || this;
  82595. }
  82596. /**
  82597. * Gets a string describing the action executed by the current optimization
  82598. * @return description string
  82599. */
  82600. LensFlaresOptimization.prototype.getDescription = function () {
  82601. return "Turning lens flares on/off";
  82602. };
  82603. /**
  82604. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82605. * @param scene defines the current scene where to apply this optimization
  82606. * @param optimizer defines the current optimizer
  82607. * @returns true if everything that can be done was applied
  82608. */
  82609. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82610. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82611. return true;
  82612. };
  82613. ;
  82614. return LensFlaresOptimization;
  82615. }(SceneOptimization));
  82616. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82617. /**
  82618. * Defines an optimization based on user defined callback.
  82619. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82620. */
  82621. var CustomOptimization = /** @class */ (function (_super) {
  82622. __extends(CustomOptimization, _super);
  82623. function CustomOptimization() {
  82624. return _super !== null && _super.apply(this, arguments) || this;
  82625. }
  82626. /**
  82627. * Gets a string describing the action executed by the current optimization
  82628. * @returns description string
  82629. */
  82630. CustomOptimization.prototype.getDescription = function () {
  82631. if (this.onGetDescription) {
  82632. return this.onGetDescription();
  82633. }
  82634. return "Running user defined callback";
  82635. };
  82636. /**
  82637. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82638. * @param scene defines the current scene where to apply this optimization
  82639. * @param optimizer defines the current optimizer
  82640. * @returns true if everything that can be done was applied
  82641. */
  82642. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82643. if (this.onApply) {
  82644. return this.onApply(scene, optimizer);
  82645. }
  82646. return true;
  82647. };
  82648. ;
  82649. return CustomOptimization;
  82650. }(SceneOptimization));
  82651. BABYLON.CustomOptimization = CustomOptimization;
  82652. /**
  82653. * Defines an optimization used to turn particles off
  82654. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82655. */
  82656. var ParticlesOptimization = /** @class */ (function (_super) {
  82657. __extends(ParticlesOptimization, _super);
  82658. function ParticlesOptimization() {
  82659. return _super !== null && _super.apply(this, arguments) || this;
  82660. }
  82661. /**
  82662. * Gets a string describing the action executed by the current optimization
  82663. * @return description string
  82664. */
  82665. ParticlesOptimization.prototype.getDescription = function () {
  82666. return "Turning particles on/off";
  82667. };
  82668. /**
  82669. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82670. * @param scene defines the current scene where to apply this optimization
  82671. * @param optimizer defines the current optimizer
  82672. * @returns true if everything that can be done was applied
  82673. */
  82674. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82675. scene.particlesEnabled = optimizer.isInImprovementMode;
  82676. return true;
  82677. };
  82678. ;
  82679. return ParticlesOptimization;
  82680. }(SceneOptimization));
  82681. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82682. /**
  82683. * Defines an optimization used to turn render targets off
  82684. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82685. */
  82686. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82687. __extends(RenderTargetsOptimization, _super);
  82688. function RenderTargetsOptimization() {
  82689. return _super !== null && _super.apply(this, arguments) || this;
  82690. }
  82691. /**
  82692. * Gets a string describing the action executed by the current optimization
  82693. * @return description string
  82694. */
  82695. RenderTargetsOptimization.prototype.getDescription = function () {
  82696. return "Turning render targets off";
  82697. };
  82698. /**
  82699. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82700. * @param scene defines the current scene where to apply this optimization
  82701. * @param optimizer defines the current optimizer
  82702. * @returns true if everything that can be done was applied
  82703. */
  82704. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82705. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82706. return true;
  82707. };
  82708. ;
  82709. return RenderTargetsOptimization;
  82710. }(SceneOptimization));
  82711. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82712. /**
  82713. * Defines an optimization used to merge meshes with compatible materials
  82714. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82715. */
  82716. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82717. __extends(MergeMeshesOptimization, _super);
  82718. function MergeMeshesOptimization() {
  82719. var _this = _super !== null && _super.apply(this, arguments) || this;
  82720. _this._canBeMerged = function (abstractMesh) {
  82721. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82722. return false;
  82723. }
  82724. var mesh = abstractMesh;
  82725. if (!mesh.isVisible || !mesh.isEnabled()) {
  82726. return false;
  82727. }
  82728. if (mesh.instances.length > 0) {
  82729. return false;
  82730. }
  82731. if (mesh.skeleton || mesh.hasLODLevels) {
  82732. return false;
  82733. }
  82734. if (mesh.parent) {
  82735. return false;
  82736. }
  82737. return true;
  82738. };
  82739. return _this;
  82740. }
  82741. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82742. /**
  82743. * Gets or sets a boolean which defines if optimization octree has to be updated
  82744. */
  82745. get: function () {
  82746. return MergeMeshesOptimization._UpdateSelectionTree;
  82747. },
  82748. /**
  82749. * Gets or sets a boolean which defines if optimization octree has to be updated
  82750. */
  82751. set: function (value) {
  82752. MergeMeshesOptimization._UpdateSelectionTree = value;
  82753. },
  82754. enumerable: true,
  82755. configurable: true
  82756. });
  82757. /**
  82758. * Gets a string describing the action executed by the current optimization
  82759. * @return description string
  82760. */
  82761. MergeMeshesOptimization.prototype.getDescription = function () {
  82762. return "Merging similar meshes together";
  82763. };
  82764. /**
  82765. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82766. * @param scene defines the current scene where to apply this optimization
  82767. * @param optimizer defines the current optimizer
  82768. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82769. * @returns true if everything that can be done was applied
  82770. */
  82771. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82772. var globalPool = scene.meshes.slice(0);
  82773. var globalLength = globalPool.length;
  82774. for (var index = 0; index < globalLength; index++) {
  82775. var currentPool = new Array();
  82776. var current = globalPool[index];
  82777. // Checks
  82778. if (!this._canBeMerged(current)) {
  82779. continue;
  82780. }
  82781. currentPool.push(current);
  82782. // Find compatible meshes
  82783. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82784. var otherMesh = globalPool[subIndex];
  82785. if (!this._canBeMerged(otherMesh)) {
  82786. continue;
  82787. }
  82788. if (otherMesh.material !== current.material) {
  82789. continue;
  82790. }
  82791. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82792. continue;
  82793. }
  82794. currentPool.push(otherMesh);
  82795. globalLength--;
  82796. globalPool.splice(subIndex, 1);
  82797. subIndex--;
  82798. }
  82799. if (currentPool.length < 2) {
  82800. continue;
  82801. }
  82802. // Merge meshes
  82803. BABYLON.Mesh.MergeMeshes(currentPool);
  82804. }
  82805. if (updateSelectionTree != undefined) {
  82806. if (updateSelectionTree) {
  82807. scene.createOrUpdateSelectionOctree();
  82808. }
  82809. }
  82810. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82811. scene.createOrUpdateSelectionOctree();
  82812. }
  82813. return true;
  82814. };
  82815. ;
  82816. MergeMeshesOptimization._UpdateSelectionTree = false;
  82817. return MergeMeshesOptimization;
  82818. }(SceneOptimization));
  82819. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82820. /**
  82821. * Defines a list of options used by SceneOptimizer
  82822. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82823. */
  82824. var SceneOptimizerOptions = /** @class */ (function () {
  82825. /**
  82826. * Creates a new list of options used by SceneOptimizer
  82827. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82828. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82829. */
  82830. function SceneOptimizerOptions(
  82831. /**
  82832. * Defines the target frame rate to reach (60 by default)
  82833. */
  82834. targetFrameRate,
  82835. /**
  82836. * Defines the interval between two checkes (2000ms by default)
  82837. */
  82838. trackerDuration) {
  82839. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82840. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82841. this.targetFrameRate = targetFrameRate;
  82842. this.trackerDuration = trackerDuration;
  82843. /**
  82844. * Gets the list of optimizations to apply
  82845. */
  82846. this.optimizations = new Array();
  82847. }
  82848. /**
  82849. * Add a new optimization
  82850. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82851. * @returns the current SceneOptimizerOptions
  82852. */
  82853. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82854. this.optimizations.push(optimization);
  82855. return this;
  82856. };
  82857. /**
  82858. * Add a new custom optimization
  82859. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82860. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82861. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82862. * @returns the current SceneOptimizerOptions
  82863. */
  82864. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82865. if (priority === void 0) { priority = 0; }
  82866. var optimization = new CustomOptimization(priority);
  82867. optimization.onApply = onApply;
  82868. optimization.onGetDescription = onGetDescription;
  82869. this.optimizations.push(optimization);
  82870. return this;
  82871. };
  82872. /**
  82873. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82874. * @param targetFrameRate defines the target frame rate (60 by default)
  82875. * @returns a SceneOptimizerOptions object
  82876. */
  82877. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82878. var result = new SceneOptimizerOptions(targetFrameRate);
  82879. var priority = 0;
  82880. result.addOptimization(new MergeMeshesOptimization(priority));
  82881. result.addOptimization(new ShadowsOptimization(priority));
  82882. result.addOptimization(new LensFlaresOptimization(priority));
  82883. // Next priority
  82884. priority++;
  82885. result.addOptimization(new PostProcessesOptimization(priority));
  82886. result.addOptimization(new ParticlesOptimization(priority));
  82887. // Next priority
  82888. priority++;
  82889. result.addOptimization(new TextureOptimization(priority, 1024));
  82890. return result;
  82891. };
  82892. /**
  82893. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82894. * @param targetFrameRate defines the target frame rate (60 by default)
  82895. * @returns a SceneOptimizerOptions object
  82896. */
  82897. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82898. var result = new SceneOptimizerOptions(targetFrameRate);
  82899. var priority = 0;
  82900. result.addOptimization(new MergeMeshesOptimization(priority));
  82901. result.addOptimization(new ShadowsOptimization(priority));
  82902. result.addOptimization(new LensFlaresOptimization(priority));
  82903. // Next priority
  82904. priority++;
  82905. result.addOptimization(new PostProcessesOptimization(priority));
  82906. result.addOptimization(new ParticlesOptimization(priority));
  82907. // Next priority
  82908. priority++;
  82909. result.addOptimization(new TextureOptimization(priority, 512));
  82910. // Next priority
  82911. priority++;
  82912. result.addOptimization(new RenderTargetsOptimization(priority));
  82913. // Next priority
  82914. priority++;
  82915. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82916. return result;
  82917. };
  82918. /**
  82919. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82920. * @param targetFrameRate defines the target frame rate (60 by default)
  82921. * @returns a SceneOptimizerOptions object
  82922. */
  82923. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82924. var result = new SceneOptimizerOptions(targetFrameRate);
  82925. var priority = 0;
  82926. result.addOptimization(new MergeMeshesOptimization(priority));
  82927. result.addOptimization(new ShadowsOptimization(priority));
  82928. result.addOptimization(new LensFlaresOptimization(priority));
  82929. // Next priority
  82930. priority++;
  82931. result.addOptimization(new PostProcessesOptimization(priority));
  82932. result.addOptimization(new ParticlesOptimization(priority));
  82933. // Next priority
  82934. priority++;
  82935. result.addOptimization(new TextureOptimization(priority, 256));
  82936. // Next priority
  82937. priority++;
  82938. result.addOptimization(new RenderTargetsOptimization(priority));
  82939. // Next priority
  82940. priority++;
  82941. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82942. return result;
  82943. };
  82944. return SceneOptimizerOptions;
  82945. }());
  82946. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  82947. /**
  82948. * Class used to run optimizations in order to reach a target frame rate
  82949. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82950. */
  82951. var SceneOptimizer = /** @class */ (function () {
  82952. /**
  82953. * Creates a new SceneOptimizer
  82954. * @param scene defines the scene to work on
  82955. * @param options defines the options to use with the SceneOptimizer
  82956. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  82957. * @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)
  82958. */
  82959. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  82960. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  82961. if (improvementMode === void 0) { improvementMode = false; }
  82962. var _this = this;
  82963. this._isRunning = false;
  82964. this._currentPriorityLevel = 0;
  82965. this._targetFrameRate = 60;
  82966. this._trackerDuration = 2000;
  82967. this._currentFrameRate = 0;
  82968. this._improvementMode = false;
  82969. /**
  82970. * Defines an observable called when the optimizer reaches the target frame rate
  82971. */
  82972. this.onSuccessObservable = new BABYLON.Observable();
  82973. /**
  82974. * Defines an observable called when the optimizer enables an optimization
  82975. */
  82976. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  82977. /**
  82978. * Defines an observable called when the optimizer is not able to reach the target frame rate
  82979. */
  82980. this.onFailureObservable = new BABYLON.Observable();
  82981. if (!options) {
  82982. this._options = new SceneOptimizerOptions();
  82983. }
  82984. else {
  82985. this._options = options;
  82986. }
  82987. if (this._options.targetFrameRate) {
  82988. this._targetFrameRate = this._options.targetFrameRate;
  82989. }
  82990. if (this._options.trackerDuration) {
  82991. this._trackerDuration = this._options.trackerDuration;
  82992. }
  82993. if (autoGeneratePriorities) {
  82994. var priority = 0;
  82995. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  82996. var optim = _a[_i];
  82997. optim.priority = priority++;
  82998. }
  82999. }
  83000. this._improvementMode = improvementMode;
  83001. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83002. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83003. _this._sceneDisposeObserver = null;
  83004. _this.dispose();
  83005. });
  83006. }
  83007. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83008. /**
  83009. * Gets a boolean indicating if the optimizer is in improvement mode
  83010. */
  83011. get: function () {
  83012. return this._improvementMode;
  83013. },
  83014. enumerable: true,
  83015. configurable: true
  83016. });
  83017. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83018. /**
  83019. * Gets the current priority level (0 at start)
  83020. */
  83021. get: function () {
  83022. return this._currentPriorityLevel;
  83023. },
  83024. enumerable: true,
  83025. configurable: true
  83026. });
  83027. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83028. /**
  83029. * Gets the current frame rate checked by the SceneOptimizer
  83030. */
  83031. get: function () {
  83032. return this._currentFrameRate;
  83033. },
  83034. enumerable: true,
  83035. configurable: true
  83036. });
  83037. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83038. /**
  83039. * Gets or sets the current target frame rate (60 by default)
  83040. */
  83041. get: function () {
  83042. return this._targetFrameRate;
  83043. },
  83044. /**
  83045. * Gets or sets the current target frame rate (60 by default)
  83046. */
  83047. set: function (value) {
  83048. this._targetFrameRate = value;
  83049. },
  83050. enumerable: true,
  83051. configurable: true
  83052. });
  83053. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83054. /**
  83055. * Gets or sets the current interval between two checks (every 2000ms by default)
  83056. */
  83057. get: function () {
  83058. return this._trackerDuration;
  83059. },
  83060. /**
  83061. * Gets or sets the current interval between two checks (every 2000ms by default)
  83062. */
  83063. set: function (value) {
  83064. this._trackerDuration = value;
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83070. /**
  83071. * Gets the list of active optimizations
  83072. */
  83073. get: function () {
  83074. return this._options.optimizations;
  83075. },
  83076. enumerable: true,
  83077. configurable: true
  83078. });
  83079. /**
  83080. * Stops the current optimizer
  83081. */
  83082. SceneOptimizer.prototype.stop = function () {
  83083. this._isRunning = false;
  83084. };
  83085. /**
  83086. * Reset the optimizer to initial step (current priority level = 0)
  83087. */
  83088. SceneOptimizer.prototype.reset = function () {
  83089. this._currentPriorityLevel = 0;
  83090. };
  83091. /**
  83092. * Start the optimizer. By default it will try to reach a specific framerate
  83093. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83094. */
  83095. SceneOptimizer.prototype.start = function () {
  83096. var _this = this;
  83097. if (this._isRunning) {
  83098. return;
  83099. }
  83100. this._isRunning = true;
  83101. // Let's wait for the scene to be ready before running our check
  83102. this._scene.executeWhenReady(function () {
  83103. setTimeout(function () {
  83104. _this._checkCurrentState();
  83105. }, _this._trackerDuration);
  83106. });
  83107. };
  83108. SceneOptimizer.prototype._checkCurrentState = function () {
  83109. var _this = this;
  83110. if (!this._isRunning) {
  83111. return;
  83112. }
  83113. var scene = this._scene;
  83114. var options = this._options;
  83115. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83116. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83117. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83118. this._isRunning = false;
  83119. this.onSuccessObservable.notifyObservers(this);
  83120. return;
  83121. }
  83122. // Apply current level of optimizations
  83123. var allDone = true;
  83124. var noOptimizationApplied = true;
  83125. for (var index = 0; index < options.optimizations.length; index++) {
  83126. var optimization = options.optimizations[index];
  83127. if (optimization.priority === this._currentPriorityLevel) {
  83128. noOptimizationApplied = false;
  83129. allDone = allDone && optimization.apply(scene, this);
  83130. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83131. }
  83132. }
  83133. // If no optimization was applied, this is a failure :(
  83134. if (noOptimizationApplied) {
  83135. this._isRunning = false;
  83136. this.onFailureObservable.notifyObservers(this);
  83137. return;
  83138. }
  83139. // If all optimizations were done, move to next level
  83140. if (allDone) {
  83141. this._currentPriorityLevel++;
  83142. }
  83143. // Let's the system running for a specific amount of time before checking FPS
  83144. scene.executeWhenReady(function () {
  83145. setTimeout(function () {
  83146. _this._checkCurrentState();
  83147. }, _this._trackerDuration);
  83148. });
  83149. };
  83150. /**
  83151. * Release all resources
  83152. */
  83153. SceneOptimizer.prototype.dispose = function () {
  83154. this.stop();
  83155. this.onSuccessObservable.clear();
  83156. this.onFailureObservable.clear();
  83157. this.onNewOptimizationAppliedObservable.clear();
  83158. if (this._sceneDisposeObserver) {
  83159. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83160. }
  83161. };
  83162. /**
  83163. * Helper function to create a SceneOptimizer with one single line of code
  83164. * @param scene defines the scene to work on
  83165. * @param options defines the options to use with the SceneOptimizer
  83166. * @param onSuccess defines a callback to call on success
  83167. * @param onFailure defines a callback to call on failure
  83168. * @returns the new SceneOptimizer object
  83169. */
  83170. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83171. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83172. if (onSuccess) {
  83173. optimizer.onSuccessObservable.add(function () {
  83174. onSuccess();
  83175. });
  83176. }
  83177. if (onFailure) {
  83178. optimizer.onFailureObservable.add(function () {
  83179. onFailure();
  83180. });
  83181. }
  83182. optimizer.start();
  83183. return optimizer;
  83184. };
  83185. return SceneOptimizer;
  83186. }());
  83187. BABYLON.SceneOptimizer = SceneOptimizer;
  83188. })(BABYLON || (BABYLON = {}));
  83189. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83190. var BABYLON;
  83191. (function (BABYLON) {
  83192. var OutlineRenderer = /** @class */ (function () {
  83193. function OutlineRenderer(scene) {
  83194. this.zOffset = 1;
  83195. this._scene = scene;
  83196. }
  83197. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83198. var _this = this;
  83199. if (useOverlay === void 0) { useOverlay = false; }
  83200. var scene = this._scene;
  83201. var engine = this._scene.getEngine();
  83202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83203. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83204. return;
  83205. }
  83206. var mesh = subMesh.getRenderingMesh();
  83207. var material = subMesh.getMaterial();
  83208. if (!material || !scene.activeCamera) {
  83209. return;
  83210. }
  83211. engine.enableEffect(this._effect);
  83212. // Logarithmic depth
  83213. if (material.useLogarithmicDepth) {
  83214. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83215. }
  83216. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83217. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83218. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83219. // Bones
  83220. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83221. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83222. }
  83223. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83224. // Alpha test
  83225. if (material && material.needAlphaTesting()) {
  83226. var alphaTexture = material.getAlphaTestTexture();
  83227. if (alphaTexture) {
  83228. this._effect.setTexture("diffuseSampler", alphaTexture);
  83229. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83230. }
  83231. }
  83232. engine.setZOffset(-this.zOffset);
  83233. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83234. engine.setZOffset(0);
  83235. };
  83236. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83237. var defines = [];
  83238. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83239. var mesh = subMesh.getMesh();
  83240. var material = subMesh.getMaterial();
  83241. if (material) {
  83242. // Alpha test
  83243. if (material.needAlphaTesting()) {
  83244. defines.push("#define ALPHATEST");
  83245. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83246. attribs.push(BABYLON.VertexBuffer.UVKind);
  83247. defines.push("#define UV1");
  83248. }
  83249. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83250. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83251. defines.push("#define UV2");
  83252. }
  83253. }
  83254. //Logarithmic depth
  83255. if (material.useLogarithmicDepth) {
  83256. defines.push("#define LOGARITHMICDEPTH");
  83257. }
  83258. }
  83259. // Bones
  83260. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83261. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83262. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83263. if (mesh.numBoneInfluencers > 4) {
  83264. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83265. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83266. }
  83267. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83268. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83269. }
  83270. else {
  83271. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83272. }
  83273. // Instances
  83274. if (useInstances) {
  83275. defines.push("#define INSTANCES");
  83276. attribs.push("world0");
  83277. attribs.push("world1");
  83278. attribs.push("world2");
  83279. attribs.push("world3");
  83280. }
  83281. // Get correct effect
  83282. var join = defines.join("\n");
  83283. if (this._cachedDefines !== join) {
  83284. this._cachedDefines = join;
  83285. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83286. }
  83287. return this._effect.isReady();
  83288. };
  83289. return OutlineRenderer;
  83290. }());
  83291. BABYLON.OutlineRenderer = OutlineRenderer;
  83292. })(BABYLON || (BABYLON = {}));
  83293. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83294. var BABYLON;
  83295. (function (BABYLON) {
  83296. var FaceAdjacencies = /** @class */ (function () {
  83297. function FaceAdjacencies() {
  83298. this.edges = new Array();
  83299. this.edgesConnectedCount = 0;
  83300. }
  83301. return FaceAdjacencies;
  83302. }());
  83303. var EdgesRenderer = /** @class */ (function () {
  83304. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83305. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83306. if (epsilon === void 0) { epsilon = 0.95; }
  83307. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83308. this.edgesWidthScalerForOrthographic = 1000.0;
  83309. this.edgesWidthScalerForPerspective = 50.0;
  83310. this._linesPositions = new Array();
  83311. this._linesNormals = new Array();
  83312. this._linesIndices = new Array();
  83313. this._buffers = {};
  83314. this._checkVerticesInsteadOfIndices = false;
  83315. this._source = source;
  83316. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83317. this._epsilon = epsilon;
  83318. this._prepareRessources();
  83319. this._generateEdgesLines();
  83320. }
  83321. EdgesRenderer.prototype._prepareRessources = function () {
  83322. if (this._lineShader) {
  83323. return;
  83324. }
  83325. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83326. attributes: ["position", "normal"],
  83327. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83328. });
  83329. this._lineShader.disableDepthWrite = true;
  83330. this._lineShader.backFaceCulling = false;
  83331. };
  83332. EdgesRenderer.prototype._rebuild = function () {
  83333. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83334. if (buffer) {
  83335. buffer._rebuild();
  83336. }
  83337. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83338. if (buffer) {
  83339. buffer._rebuild();
  83340. }
  83341. var scene = this._source.getScene();
  83342. var engine = scene.getEngine();
  83343. this._ib = engine.createIndexBuffer(this._linesIndices);
  83344. };
  83345. EdgesRenderer.prototype.dispose = function () {
  83346. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83347. if (buffer) {
  83348. buffer.dispose();
  83349. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83350. }
  83351. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83352. if (buffer) {
  83353. buffer.dispose();
  83354. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83355. }
  83356. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83357. this._lineShader.dispose();
  83358. };
  83359. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83360. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83361. return 0;
  83362. }
  83363. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83364. return 1;
  83365. }
  83366. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83367. return 2;
  83368. }
  83369. return -1;
  83370. };
  83371. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83372. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83373. return 0;
  83374. }
  83375. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83376. return 1;
  83377. }
  83378. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83379. return 2;
  83380. }
  83381. return -1;
  83382. };
  83383. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83384. var needToCreateLine;
  83385. if (edge === undefined) {
  83386. needToCreateLine = true;
  83387. }
  83388. else {
  83389. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83390. needToCreateLine = dotProduct < this._epsilon;
  83391. }
  83392. if (needToCreateLine) {
  83393. var offset = this._linesPositions.length / 3;
  83394. var normal = p0.subtract(p1);
  83395. normal.normalize();
  83396. // Positions
  83397. this._linesPositions.push(p0.x);
  83398. this._linesPositions.push(p0.y);
  83399. this._linesPositions.push(p0.z);
  83400. this._linesPositions.push(p0.x);
  83401. this._linesPositions.push(p0.y);
  83402. this._linesPositions.push(p0.z);
  83403. this._linesPositions.push(p1.x);
  83404. this._linesPositions.push(p1.y);
  83405. this._linesPositions.push(p1.z);
  83406. this._linesPositions.push(p1.x);
  83407. this._linesPositions.push(p1.y);
  83408. this._linesPositions.push(p1.z);
  83409. // Normals
  83410. this._linesNormals.push(p1.x);
  83411. this._linesNormals.push(p1.y);
  83412. this._linesNormals.push(p1.z);
  83413. this._linesNormals.push(-1);
  83414. this._linesNormals.push(p1.x);
  83415. this._linesNormals.push(p1.y);
  83416. this._linesNormals.push(p1.z);
  83417. this._linesNormals.push(1);
  83418. this._linesNormals.push(p0.x);
  83419. this._linesNormals.push(p0.y);
  83420. this._linesNormals.push(p0.z);
  83421. this._linesNormals.push(-1);
  83422. this._linesNormals.push(p0.x);
  83423. this._linesNormals.push(p0.y);
  83424. this._linesNormals.push(p0.z);
  83425. this._linesNormals.push(1);
  83426. // Indices
  83427. this._linesIndices.push(offset);
  83428. this._linesIndices.push(offset + 1);
  83429. this._linesIndices.push(offset + 2);
  83430. this._linesIndices.push(offset);
  83431. this._linesIndices.push(offset + 2);
  83432. this._linesIndices.push(offset + 3);
  83433. }
  83434. };
  83435. EdgesRenderer.prototype._generateEdgesLines = function () {
  83436. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83437. var indices = this._source.getIndices();
  83438. if (!indices || !positions) {
  83439. return;
  83440. }
  83441. // First let's find adjacencies
  83442. var adjacencies = new Array();
  83443. var faceNormals = new Array();
  83444. var index;
  83445. var faceAdjacencies;
  83446. // Prepare faces
  83447. for (index = 0; index < indices.length; index += 3) {
  83448. faceAdjacencies = new FaceAdjacencies();
  83449. var p0Index = indices[index];
  83450. var p1Index = indices[index + 1];
  83451. var p2Index = indices[index + 2];
  83452. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83453. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83454. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83455. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83456. faceNormal.normalize();
  83457. faceNormals.push(faceNormal);
  83458. adjacencies.push(faceAdjacencies);
  83459. }
  83460. // Scan
  83461. for (index = 0; index < adjacencies.length; index++) {
  83462. faceAdjacencies = adjacencies[index];
  83463. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83464. var otherFaceAdjacencies = adjacencies[otherIndex];
  83465. if (faceAdjacencies.edgesConnectedCount === 3) {
  83466. break;
  83467. }
  83468. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83469. continue;
  83470. }
  83471. var otherP0 = indices[otherIndex * 3];
  83472. var otherP1 = indices[otherIndex * 3 + 1];
  83473. var otherP2 = indices[otherIndex * 3 + 2];
  83474. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83475. var otherEdgeIndex = 0;
  83476. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83477. continue;
  83478. }
  83479. switch (edgeIndex) {
  83480. case 0:
  83481. if (this._checkVerticesInsteadOfIndices) {
  83482. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83483. }
  83484. else {
  83485. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83486. }
  83487. break;
  83488. case 1:
  83489. if (this._checkVerticesInsteadOfIndices) {
  83490. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83491. }
  83492. else {
  83493. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83494. }
  83495. break;
  83496. case 2:
  83497. if (this._checkVerticesInsteadOfIndices) {
  83498. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83499. }
  83500. else {
  83501. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83502. }
  83503. break;
  83504. }
  83505. if (otherEdgeIndex === -1) {
  83506. continue;
  83507. }
  83508. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83509. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83510. faceAdjacencies.edgesConnectedCount++;
  83511. otherFaceAdjacencies.edgesConnectedCount++;
  83512. if (faceAdjacencies.edgesConnectedCount === 3) {
  83513. break;
  83514. }
  83515. }
  83516. }
  83517. }
  83518. // Create lines
  83519. for (index = 0; index < adjacencies.length; index++) {
  83520. // 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
  83521. var current = adjacencies[index];
  83522. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83523. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83524. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83525. }
  83526. // Merge into a single mesh
  83527. var engine = this._source.getScene().getEngine();
  83528. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83529. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83530. this._ib = engine.createIndexBuffer(this._linesIndices);
  83531. this._indicesCount = this._linesIndices.length;
  83532. };
  83533. EdgesRenderer.prototype.render = function () {
  83534. var scene = this._source.getScene();
  83535. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83536. return;
  83537. }
  83538. var engine = scene.getEngine();
  83539. this._lineShader._preBind();
  83540. // VBOs
  83541. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83542. scene.resetCachedMaterial();
  83543. this._lineShader.setColor4("color", this._source.edgesColor);
  83544. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83545. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83546. }
  83547. else {
  83548. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83549. }
  83550. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83551. this._lineShader.bind(this._source.getWorldMatrix());
  83552. // Draw order
  83553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83554. this._lineShader.unbind();
  83555. engine.setDepthWrite(true);
  83556. };
  83557. return EdgesRenderer;
  83558. }());
  83559. BABYLON.EdgesRenderer = EdgesRenderer;
  83560. })(BABYLON || (BABYLON = {}));
  83561. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83562. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83563. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83564. s = arguments[i];
  83565. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83566. t[p] = s[p];
  83567. }
  83568. return t;
  83569. };
  83570. var BABYLON;
  83571. (function (BABYLON) {
  83572. /**
  83573. * The effect layer Helps adding post process effect blended with the main pass.
  83574. *
  83575. * This can be for instance use to generate glow or higlight effects on the scene.
  83576. *
  83577. * The effect layer class can not be used directly and is intented to inherited from to be
  83578. * customized per effects.
  83579. */
  83580. var EffectLayer = /** @class */ (function () {
  83581. /**
  83582. * Instantiates a new effect Layer and references it in the scene.
  83583. * @param name The name of the layer
  83584. * @param scene The scene to use the layer in
  83585. */
  83586. function EffectLayer(
  83587. /** The Friendly of the effect in the scene */
  83588. name, scene) {
  83589. this.name = name;
  83590. this._vertexBuffers = {};
  83591. this._maxSize = 0;
  83592. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83593. this._shouldRender = true;
  83594. this._postProcesses = [];
  83595. this._textures = [];
  83596. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83597. /**
  83598. * The clear color of the texture used to generate the glow map.
  83599. */
  83600. this.neutralColor = new BABYLON.Color4();
  83601. /**
  83602. * Specifies wether the highlight layer is enabled or not.
  83603. */
  83604. this.isEnabled = true;
  83605. /**
  83606. * An event triggered when the effect layer has been disposed.
  83607. */
  83608. this.onDisposeObservable = new BABYLON.Observable();
  83609. /**
  83610. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83611. */
  83612. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83613. /**
  83614. * An event triggered when the generated texture is being merged in the scene.
  83615. */
  83616. this.onBeforeComposeObservable = new BABYLON.Observable();
  83617. /**
  83618. * An event triggered when the generated texture has been merged in the scene.
  83619. */
  83620. this.onAfterComposeObservable = new BABYLON.Observable();
  83621. /**
  83622. * An event triggered when the efffect layer changes its size.
  83623. */
  83624. this.onSizeChangedObservable = new BABYLON.Observable();
  83625. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83626. this._engine = scene.getEngine();
  83627. this._maxSize = this._engine.getCaps().maxTextureSize;
  83628. this._scene.effectLayers.push(this);
  83629. // Generate Buffers
  83630. this._generateIndexBuffer();
  83631. this._genrateVertexBuffer();
  83632. }
  83633. Object.defineProperty(EffectLayer.prototype, "camera", {
  83634. /**
  83635. * Gets the camera attached to the layer.
  83636. */
  83637. get: function () {
  83638. return this._effectLayerOptions.camera;
  83639. },
  83640. enumerable: true,
  83641. configurable: true
  83642. });
  83643. /**
  83644. * Initializes the effect layer with the required options.
  83645. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83646. */
  83647. EffectLayer.prototype._init = function (options) {
  83648. // Adapt options
  83649. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83650. this._setMainTextureSize();
  83651. this._createMainTexture();
  83652. this._createTextureAndPostProcesses();
  83653. this._mergeEffect = this._createMergeEffect();
  83654. };
  83655. /**
  83656. * Generates the index buffer of the full screen quad blending to the main canvas.
  83657. */
  83658. EffectLayer.prototype._generateIndexBuffer = function () {
  83659. // Indices
  83660. var indices = [];
  83661. indices.push(0);
  83662. indices.push(1);
  83663. indices.push(2);
  83664. indices.push(0);
  83665. indices.push(2);
  83666. indices.push(3);
  83667. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83668. };
  83669. /**
  83670. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83671. */
  83672. EffectLayer.prototype._genrateVertexBuffer = function () {
  83673. // VBO
  83674. var vertices = [];
  83675. vertices.push(1, 1);
  83676. vertices.push(-1, 1);
  83677. vertices.push(-1, -1);
  83678. vertices.push(1, -1);
  83679. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83680. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83681. };
  83682. /**
  83683. * Sets the main texture desired size which is the closest power of two
  83684. * of the engine canvas size.
  83685. */
  83686. EffectLayer.prototype._setMainTextureSize = function () {
  83687. if (this._effectLayerOptions.mainTextureFixedSize) {
  83688. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83689. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83690. }
  83691. else {
  83692. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83693. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83694. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83695. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83696. }
  83697. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83698. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83699. };
  83700. /**
  83701. * Creates the main texture for the effect layer.
  83702. */
  83703. EffectLayer.prototype._createMainTexture = function () {
  83704. var _this = this;
  83705. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83706. width: this._mainTextureDesiredSize.width,
  83707. height: this._mainTextureDesiredSize.height
  83708. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83709. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83710. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83711. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83712. this._mainTexture.anisotropicFilteringLevel = 1;
  83713. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83714. this._mainTexture.renderParticles = false;
  83715. this._mainTexture.renderList = null;
  83716. this._mainTexture.ignoreCameraViewport = true;
  83717. // Custom render function
  83718. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83719. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83720. var index;
  83721. var engine = _this._scene.getEngine();
  83722. if (depthOnlySubMeshes.length) {
  83723. engine.setColorWrite(false);
  83724. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83725. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83726. }
  83727. engine.setColorWrite(true);
  83728. }
  83729. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83730. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83731. }
  83732. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83733. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83734. }
  83735. for (index = 0; index < transparentSubMeshes.length; index++) {
  83736. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83737. }
  83738. };
  83739. this._mainTexture.onClearObservable.add(function (engine) {
  83740. engine.clear(_this.neutralColor, true, true, true);
  83741. });
  83742. };
  83743. /**
  83744. * Checks for the readiness of the element composing the layer.
  83745. * @param subMesh the mesh to check for
  83746. * @param useInstances specify wether or not to use instances to render the mesh
  83747. * @param emissiveTexture the associated emissive texture used to generate the glow
  83748. * @return true if ready otherwise, false
  83749. */
  83750. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83751. var material = subMesh.getMaterial();
  83752. if (!material) {
  83753. return false;
  83754. }
  83755. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83756. return false;
  83757. }
  83758. var defines = [];
  83759. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83760. var mesh = subMesh.getMesh();
  83761. var uv1 = false;
  83762. var uv2 = false;
  83763. // Alpha test
  83764. if (material && material.needAlphaTesting()) {
  83765. var alphaTexture = material.getAlphaTestTexture();
  83766. if (alphaTexture) {
  83767. defines.push("#define ALPHATEST");
  83768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83769. alphaTexture.coordinatesIndex === 1) {
  83770. defines.push("#define DIFFUSEUV2");
  83771. uv2 = true;
  83772. }
  83773. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83774. defines.push("#define DIFFUSEUV1");
  83775. uv1 = true;
  83776. }
  83777. }
  83778. }
  83779. // Emissive
  83780. if (emissiveTexture) {
  83781. defines.push("#define EMISSIVE");
  83782. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83783. emissiveTexture.coordinatesIndex === 1) {
  83784. defines.push("#define EMISSIVEUV2");
  83785. uv2 = true;
  83786. }
  83787. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83788. defines.push("#define EMISSIVEUV1");
  83789. uv1 = true;
  83790. }
  83791. }
  83792. if (uv1) {
  83793. attribs.push(BABYLON.VertexBuffer.UVKind);
  83794. defines.push("#define UV1");
  83795. }
  83796. if (uv2) {
  83797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83798. defines.push("#define UV2");
  83799. }
  83800. // Bones
  83801. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83802. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83803. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83804. if (mesh.numBoneInfluencers > 4) {
  83805. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83806. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83807. }
  83808. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83809. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83810. }
  83811. else {
  83812. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83813. }
  83814. // Instances
  83815. if (useInstances) {
  83816. defines.push("#define INSTANCES");
  83817. attribs.push("world0");
  83818. attribs.push("world1");
  83819. attribs.push("world2");
  83820. attribs.push("world3");
  83821. }
  83822. // Get correct effect
  83823. var join = defines.join("\n");
  83824. if (this._cachedDefines !== join) {
  83825. this._cachedDefines = join;
  83826. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83827. }
  83828. return this._effectLayerMapGenerationEffect.isReady();
  83829. };
  83830. /**
  83831. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83832. */
  83833. EffectLayer.prototype.render = function () {
  83834. var currentEffect = this._mergeEffect;
  83835. // Check
  83836. if (!currentEffect.isReady())
  83837. return;
  83838. for (var i = 0; i < this._postProcesses.length; i++) {
  83839. if (!this._postProcesses[i].isReady()) {
  83840. return;
  83841. }
  83842. }
  83843. var engine = this._scene.getEngine();
  83844. this.onBeforeComposeObservable.notifyObservers(this);
  83845. // Render
  83846. engine.enableEffect(currentEffect);
  83847. engine.setState(false);
  83848. // VBOs
  83849. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83850. // Cache
  83851. var previousAlphaMode = engine.getAlphaMode();
  83852. // Go Blend.
  83853. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83854. // Blends the map on the main canvas.
  83855. this._internalRender(currentEffect);
  83856. // Restore Alpha
  83857. engine.setAlphaMode(previousAlphaMode);
  83858. this.onAfterComposeObservable.notifyObservers(this);
  83859. // Handle size changes.
  83860. var size = this._mainTexture.getSize();
  83861. this._setMainTextureSize();
  83862. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83863. // Recreate RTT and post processes on size change.
  83864. this.onSizeChangedObservable.notifyObservers(this);
  83865. this._disposeTextureAndPostProcesses();
  83866. this._createMainTexture();
  83867. this._createTextureAndPostProcesses();
  83868. }
  83869. };
  83870. /**
  83871. * Determine if a given mesh will be used in the current effect.
  83872. * @param mesh mesh to test
  83873. * @returns true if the mesh will be used
  83874. */
  83875. EffectLayer.prototype.hasMesh = function (mesh) {
  83876. return true;
  83877. };
  83878. /**
  83879. * Returns true if the layer contains information to display, otherwise false.
  83880. * @returns true if the glow layer should be rendered
  83881. */
  83882. EffectLayer.prototype.shouldRender = function () {
  83883. return this.isEnabled && this._shouldRender;
  83884. };
  83885. /**
  83886. * Returns true if the mesh should render, otherwise false.
  83887. * @param mesh The mesh to render
  83888. * @returns true if it should render otherwise false
  83889. */
  83890. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83891. return true;
  83892. };
  83893. /**
  83894. * Returns true if the mesh should render, otherwise false.
  83895. * @param mesh The mesh to render
  83896. * @returns true if it should render otherwise false
  83897. */
  83898. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83899. return true;
  83900. };
  83901. /**
  83902. * Renders the submesh passed in parameter to the generation map.
  83903. */
  83904. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83905. var _this = this;
  83906. if (!this.shouldRender()) {
  83907. return;
  83908. }
  83909. var material = subMesh.getMaterial();
  83910. var mesh = subMesh.getRenderingMesh();
  83911. var scene = this._scene;
  83912. var engine = scene.getEngine();
  83913. if (!material) {
  83914. return;
  83915. }
  83916. // Do not block in blend mode.
  83917. if (material.needAlphaBlendingForMesh(mesh)) {
  83918. return;
  83919. }
  83920. // Culling
  83921. engine.setState(material.backFaceCulling);
  83922. // Managing instances
  83923. var batch = mesh._getInstancesRenderList(subMesh._id);
  83924. if (batch.mustReturn) {
  83925. return;
  83926. }
  83927. // Early Exit per mesh
  83928. if (!this._shouldRenderMesh(mesh)) {
  83929. return;
  83930. }
  83931. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83932. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83933. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83934. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83935. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83936. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83937. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83938. // Alpha test
  83939. if (material && material.needAlphaTesting()) {
  83940. var alphaTexture = material.getAlphaTestTexture();
  83941. if (alphaTexture) {
  83942. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  83943. var textureMatrix = alphaTexture.getTextureMatrix();
  83944. if (textureMatrix) {
  83945. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  83946. }
  83947. }
  83948. }
  83949. // Glow emissive only
  83950. if (this._emissiveTextureAndColor.texture) {
  83951. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  83952. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  83953. }
  83954. // Bones
  83955. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83956. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83957. }
  83958. // Draw
  83959. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  83960. }
  83961. else {
  83962. // Need to reset refresh rate of the shadowMap
  83963. this._mainTexture.resetRefreshCounter();
  83964. }
  83965. };
  83966. /**
  83967. * Rebuild the required buffers.
  83968. * @ignore Internal use only.
  83969. */
  83970. EffectLayer.prototype._rebuild = function () {
  83971. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83972. if (vb) {
  83973. vb._rebuild();
  83974. }
  83975. this._generateIndexBuffer();
  83976. };
  83977. /**
  83978. * Dispose only the render target textures and post process.
  83979. */
  83980. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  83981. this._mainTexture.dispose();
  83982. for (var i = 0; i < this._postProcesses.length; i++) {
  83983. if (this._postProcesses[i]) {
  83984. this._postProcesses[i].dispose();
  83985. }
  83986. }
  83987. this._postProcesses = [];
  83988. for (var i = 0; i < this._textures.length; i++) {
  83989. if (this._textures[i]) {
  83990. this._textures[i].dispose();
  83991. }
  83992. }
  83993. this._textures = [];
  83994. };
  83995. /**
  83996. * Dispose the highlight layer and free resources.
  83997. */
  83998. EffectLayer.prototype.dispose = function () {
  83999. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84000. if (vertexBuffer) {
  84001. vertexBuffer.dispose();
  84002. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84003. }
  84004. if (this._indexBuffer) {
  84005. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84006. this._indexBuffer = null;
  84007. }
  84008. // Clean textures and post processes
  84009. this._disposeTextureAndPostProcesses();
  84010. // Remove from scene
  84011. var index = this._scene.effectLayers.indexOf(this, 0);
  84012. if (index > -1) {
  84013. this._scene.effectLayers.splice(index, 1);
  84014. }
  84015. // Callback
  84016. this.onDisposeObservable.notifyObservers(this);
  84017. this.onDisposeObservable.clear();
  84018. this.onBeforeRenderMainTextureObservable.clear();
  84019. this.onBeforeComposeObservable.clear();
  84020. this.onAfterComposeObservable.clear();
  84021. this.onSizeChangedObservable.clear();
  84022. };
  84023. return EffectLayer;
  84024. }());
  84025. BABYLON.EffectLayer = EffectLayer;
  84026. })(BABYLON || (BABYLON = {}));
  84027. //# sourceMappingURL=babylon.effectLayer.js.map
  84028. var BABYLON;
  84029. (function (BABYLON) {
  84030. /**
  84031. * Special Glow Blur post process only blurring the alpha channel
  84032. * It enforces keeping the most luminous color in the color channel.
  84033. */
  84034. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84035. __extends(GlowBlurPostProcess, _super);
  84036. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84038. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84039. _this.direction = direction;
  84040. _this.kernel = kernel;
  84041. _this.onApplyObservable.add(function (effect) {
  84042. effect.setFloat2("screenSize", _this.width, _this.height);
  84043. effect.setVector2("direction", _this.direction);
  84044. effect.setFloat("blurWidth", _this.kernel);
  84045. });
  84046. return _this;
  84047. }
  84048. return GlowBlurPostProcess;
  84049. }(BABYLON.PostProcess));
  84050. /**
  84051. * The highlight layer Helps adding a glow effect around a mesh.
  84052. *
  84053. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84054. * glowy meshes to your scene.
  84055. *
  84056. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84057. */
  84058. var HighlightLayer = /** @class */ (function (_super) {
  84059. __extends(HighlightLayer, _super);
  84060. /**
  84061. * Instantiates a new highlight Layer and references it to the scene..
  84062. * @param name The name of the layer
  84063. * @param scene The scene to use the layer in
  84064. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84065. */
  84066. function HighlightLayer(name, scene, options) {
  84067. var _this = _super.call(this, name, scene) || this;
  84068. _this.name = name;
  84069. /**
  84070. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84071. */
  84072. _this.innerGlow = true;
  84073. /**
  84074. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84075. */
  84076. _this.outerGlow = true;
  84077. /**
  84078. * An event triggered when the highlight layer is being blurred.
  84079. */
  84080. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84081. /**
  84082. * An event triggered when the highlight layer has been blurred.
  84083. */
  84084. _this.onAfterBlurObservable = new BABYLON.Observable();
  84085. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84086. _this._meshes = {};
  84087. _this._excludedMeshes = {};
  84088. _this.neutralColor = HighlightLayer.NeutralColor;
  84089. // Warn on stencil
  84090. if (!_this._engine.isStencilEnable) {
  84091. 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 }");
  84092. }
  84093. // Adapt options
  84094. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84095. // Initialize the layer
  84096. _this._init({
  84097. alphaBlendingMode: _this._options.alphaBlendingMode,
  84098. camera: _this._options.camera,
  84099. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84100. mainTextureRatio: _this._options.mainTextureRatio
  84101. });
  84102. // Do not render as long as no meshes have been added
  84103. _this._shouldRender = false;
  84104. return _this;
  84105. }
  84106. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84107. /**
  84108. * Gets the horizontal size of the blur.
  84109. */
  84110. get: function () {
  84111. return this._horizontalBlurPostprocess.kernel;
  84112. },
  84113. /**
  84114. * Specifies the horizontal size of the blur.
  84115. */
  84116. set: function (value) {
  84117. this._horizontalBlurPostprocess.kernel = value;
  84118. },
  84119. enumerable: true,
  84120. configurable: true
  84121. });
  84122. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84123. /**
  84124. * Gets the vertical size of the blur.
  84125. */
  84126. get: function () {
  84127. return this._verticalBlurPostprocess.kernel;
  84128. },
  84129. /**
  84130. * Specifies the vertical size of the blur.
  84131. */
  84132. set: function (value) {
  84133. this._verticalBlurPostprocess.kernel = value;
  84134. },
  84135. enumerable: true,
  84136. configurable: true
  84137. });
  84138. /**
  84139. * Get the effect name of the layer.
  84140. * @return The effect name
  84141. */
  84142. HighlightLayer.prototype.getEffectName = function () {
  84143. return HighlightLayer.EffectName;
  84144. };
  84145. /**
  84146. * Create the merge effect. This is the shader use to blit the information back
  84147. * to the main canvas at the end of the scene rendering.
  84148. */
  84149. HighlightLayer.prototype._createMergeEffect = function () {
  84150. // Effect
  84151. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84152. };
  84153. /**
  84154. * Creates the render target textures and post processes used in the highlight layer.
  84155. */
  84156. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84157. var _this = this;
  84158. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84159. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84160. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84161. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84162. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84163. width: blurTextureWidth,
  84164. height: blurTextureHeight
  84165. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84166. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84167. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84168. this._blurTexture.anisotropicFilteringLevel = 16;
  84169. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84170. this._blurTexture.renderParticles = false;
  84171. this._blurTexture.ignoreCameraViewport = true;
  84172. this._textures = [this._blurTexture];
  84173. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84174. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84175. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84176. effect.setTexture("textureSampler", _this._mainTexture);
  84177. });
  84178. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84179. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84180. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84181. });
  84182. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84183. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84184. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84185. });
  84186. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84187. }
  84188. else {
  84189. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84190. width: blurTextureWidth,
  84191. height: blurTextureHeight
  84192. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84193. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84194. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84195. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84196. effect.setTexture("textureSampler", _this._mainTexture);
  84197. });
  84198. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84199. width: blurTextureWidth,
  84200. height: blurTextureHeight
  84201. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84202. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84203. }
  84204. this._mainTexture.onAfterUnbindObservable.add(function () {
  84205. _this.onBeforeBlurObservable.notifyObservers(_this);
  84206. var internalTexture = _this._blurTexture.getInternalTexture();
  84207. if (internalTexture) {
  84208. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84209. }
  84210. _this.onAfterBlurObservable.notifyObservers(_this);
  84211. });
  84212. // Prevent autoClear.
  84213. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84214. };
  84215. /**
  84216. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84217. */
  84218. HighlightLayer.prototype.needStencil = function () {
  84219. return true;
  84220. };
  84221. /**
  84222. * Checks for the readiness of the element composing the layer.
  84223. * @param subMesh the mesh to check for
  84224. * @param useInstances specify wether or not to use instances to render the mesh
  84225. * @param emissiveTexture the associated emissive texture used to generate the glow
  84226. * @return true if ready otherwise, false
  84227. */
  84228. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84229. var material = subMesh.getMaterial();
  84230. var mesh = subMesh.getRenderingMesh();
  84231. if (!material || !mesh || !this._meshes) {
  84232. return false;
  84233. }
  84234. var emissiveTexture = null;
  84235. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84236. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84237. emissiveTexture = material.emissiveTexture;
  84238. }
  84239. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84240. };
  84241. /**
  84242. * Implementation specific of rendering the generating effect on the main canvas.
  84243. * @param effect The effect used to render through
  84244. */
  84245. HighlightLayer.prototype._internalRender = function (effect) {
  84246. // Texture
  84247. effect.setTexture("textureSampler", this._blurTexture);
  84248. // Cache
  84249. var engine = this._engine;
  84250. var previousStencilBuffer = engine.getStencilBuffer();
  84251. var previousStencilFunction = engine.getStencilFunction();
  84252. var previousStencilMask = engine.getStencilMask();
  84253. var previousStencilOperationPass = engine.getStencilOperationPass();
  84254. var previousStencilOperationFail = engine.getStencilOperationFail();
  84255. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84256. var previousStencilReference = engine.getStencilFunctionReference();
  84257. // Stencil operations
  84258. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84259. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84260. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84261. // Draw order
  84262. engine.setStencilMask(0x00);
  84263. engine.setStencilBuffer(true);
  84264. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84265. // 2 passes inner outer
  84266. if (this.outerGlow) {
  84267. effect.setFloat("offset", 0);
  84268. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84270. }
  84271. if (this.innerGlow) {
  84272. effect.setFloat("offset", 1);
  84273. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84274. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84275. }
  84276. // Restore Cache
  84277. engine.setStencilFunction(previousStencilFunction);
  84278. engine.setStencilMask(previousStencilMask);
  84279. engine.setStencilBuffer(previousStencilBuffer);
  84280. engine.setStencilOperationPass(previousStencilOperationPass);
  84281. engine.setStencilOperationFail(previousStencilOperationFail);
  84282. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84283. engine.setStencilFunctionReference(previousStencilReference);
  84284. };
  84285. /**
  84286. * Returns true if the layer contains information to display, otherwise false.
  84287. */
  84288. HighlightLayer.prototype.shouldRender = function () {
  84289. if (_super.prototype.shouldRender.call(this)) {
  84290. return this._meshes ? true : false;
  84291. }
  84292. return false;
  84293. };
  84294. /**
  84295. * Returns true if the mesh should render, otherwise false.
  84296. * @param mesh The mesh to render
  84297. * @returns true if it should render otherwise false
  84298. */
  84299. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84300. // Excluded Mesh
  84301. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84302. return false;
  84303. }
  84304. ;
  84305. return true;
  84306. };
  84307. /**
  84308. * Sets the required values for both the emissive texture and and the main color.
  84309. */
  84310. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84311. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84312. if (highlightLayerMesh) {
  84313. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84314. }
  84315. else {
  84316. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84317. }
  84318. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84319. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84320. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84321. }
  84322. else {
  84323. this._emissiveTextureAndColor.texture = null;
  84324. }
  84325. };
  84326. /**
  84327. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84328. * @param mesh The mesh to exclude from the highlight layer
  84329. */
  84330. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84331. if (!this._excludedMeshes) {
  84332. return;
  84333. }
  84334. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84335. if (!meshExcluded) {
  84336. this._excludedMeshes[mesh.uniqueId] = {
  84337. mesh: mesh,
  84338. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84339. mesh.getEngine().setStencilBuffer(false);
  84340. }),
  84341. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84342. mesh.getEngine().setStencilBuffer(true);
  84343. }),
  84344. };
  84345. }
  84346. };
  84347. /**
  84348. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84349. * @param mesh The mesh to highlight
  84350. */
  84351. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84352. if (!this._excludedMeshes) {
  84353. return;
  84354. }
  84355. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84356. if (meshExcluded) {
  84357. if (meshExcluded.beforeRender) {
  84358. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84359. }
  84360. if (meshExcluded.afterRender) {
  84361. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84362. }
  84363. }
  84364. this._excludedMeshes[mesh.uniqueId] = null;
  84365. };
  84366. /**
  84367. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84368. * @param mesh mesh to test
  84369. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84370. */
  84371. HighlightLayer.prototype.hasMesh = function (mesh) {
  84372. if (!this._meshes) {
  84373. return false;
  84374. }
  84375. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84376. };
  84377. /**
  84378. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84379. * @param mesh The mesh to highlight
  84380. * @param color The color of the highlight
  84381. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84382. */
  84383. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84384. var _this = this;
  84385. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84386. if (!this._meshes) {
  84387. return;
  84388. }
  84389. var meshHighlight = this._meshes[mesh.uniqueId];
  84390. if (meshHighlight) {
  84391. meshHighlight.color = color;
  84392. }
  84393. else {
  84394. this._meshes[mesh.uniqueId] = {
  84395. mesh: mesh,
  84396. color: color,
  84397. // Lambda required for capture due to Observable this context
  84398. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84399. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84400. _this._defaultStencilReference(mesh);
  84401. }
  84402. else {
  84403. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84404. }
  84405. }),
  84406. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84407. glowEmissiveOnly: glowEmissiveOnly
  84408. };
  84409. }
  84410. this._shouldRender = true;
  84411. };
  84412. /**
  84413. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84414. * @param mesh The mesh to highlight
  84415. */
  84416. HighlightLayer.prototype.removeMesh = function (mesh) {
  84417. if (!this._meshes) {
  84418. return;
  84419. }
  84420. var meshHighlight = this._meshes[mesh.uniqueId];
  84421. if (meshHighlight) {
  84422. if (meshHighlight.observerHighlight) {
  84423. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84424. }
  84425. if (meshHighlight.observerDefault) {
  84426. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84427. }
  84428. delete this._meshes[mesh.uniqueId];
  84429. }
  84430. this._shouldRender = false;
  84431. for (var meshHighlightToCheck in this._meshes) {
  84432. if (this._meshes[meshHighlightToCheck]) {
  84433. this._shouldRender = true;
  84434. break;
  84435. }
  84436. }
  84437. };
  84438. /**
  84439. * Force the stencil to the normal expected value for none glowing parts
  84440. */
  84441. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84442. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84443. };
  84444. /**
  84445. * Free any resources and references associated to a mesh.
  84446. * Internal use
  84447. * @param mesh The mesh to free.
  84448. */
  84449. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84450. this.removeMesh(mesh);
  84451. this.removeExcludedMesh(mesh);
  84452. };
  84453. /**
  84454. * Dispose the highlight layer and free resources.
  84455. */
  84456. HighlightLayer.prototype.dispose = function () {
  84457. if (this._meshes) {
  84458. // Clean mesh references
  84459. for (var id in this._meshes) {
  84460. var meshHighlight = this._meshes[id];
  84461. if (meshHighlight && meshHighlight.mesh) {
  84462. if (meshHighlight.observerHighlight) {
  84463. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84464. }
  84465. if (meshHighlight.observerDefault) {
  84466. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84467. }
  84468. }
  84469. }
  84470. this._meshes = null;
  84471. }
  84472. if (this._excludedMeshes) {
  84473. for (var id in this._excludedMeshes) {
  84474. var meshHighlight = this._excludedMeshes[id];
  84475. if (meshHighlight) {
  84476. if (meshHighlight.beforeRender) {
  84477. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84478. }
  84479. if (meshHighlight.afterRender) {
  84480. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84481. }
  84482. }
  84483. }
  84484. this._excludedMeshes = null;
  84485. }
  84486. _super.prototype.dispose.call(this);
  84487. };
  84488. /**
  84489. * Effect Name of the highlight layer.
  84490. */
  84491. HighlightLayer.EffectName = "HighlightLayer";
  84492. /**
  84493. * The neutral color used during the preparation of the glow effect.
  84494. * This is black by default as the blend operation is a blend operation.
  84495. */
  84496. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84497. /**
  84498. * Stencil value used for glowing meshes.
  84499. */
  84500. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84501. /**
  84502. * Stencil value used for the other meshes in the scene.
  84503. */
  84504. HighlightLayer.NormalMeshStencilReference = 0x01;
  84505. return HighlightLayer;
  84506. }(BABYLON.EffectLayer));
  84507. BABYLON.HighlightLayer = HighlightLayer;
  84508. })(BABYLON || (BABYLON = {}));
  84509. //# sourceMappingURL=babylon.highlightLayer.js.map
  84510. var BABYLON;
  84511. (function (BABYLON) {
  84512. /**
  84513. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84514. *
  84515. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84516. * glowy meshes to your scene.
  84517. *
  84518. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84519. */
  84520. var GlowLayer = /** @class */ (function (_super) {
  84521. __extends(GlowLayer, _super);
  84522. /**
  84523. * Instantiates a new glow Layer and references it to the scene.
  84524. * @param name The name of the layer
  84525. * @param scene The scene to use the layer in
  84526. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84527. */
  84528. function GlowLayer(name, scene, options) {
  84529. var _this = _super.call(this, name, scene) || this;
  84530. _this.name = name;
  84531. _this._intensity = 1.0;
  84532. _this._includedOnlyMeshes = [];
  84533. _this._excludedMeshes = [];
  84534. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84535. // Adapt options
  84536. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84537. // Initialize the layer
  84538. _this._init({
  84539. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84540. camera: _this._options.camera,
  84541. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84542. mainTextureRatio: _this._options.mainTextureRatio
  84543. });
  84544. return _this;
  84545. }
  84546. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84547. /**
  84548. * Gets the kernel size of the blur.
  84549. */
  84550. get: function () {
  84551. return this._horizontalBlurPostprocess1.kernel;
  84552. },
  84553. /**
  84554. * Sets the kernel size of the blur.
  84555. */
  84556. set: function (value) {
  84557. this._horizontalBlurPostprocess1.kernel = value;
  84558. this._verticalBlurPostprocess1.kernel = value;
  84559. this._horizontalBlurPostprocess2.kernel = value;
  84560. this._verticalBlurPostprocess2.kernel = value;
  84561. },
  84562. enumerable: true,
  84563. configurable: true
  84564. });
  84565. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84566. /**
  84567. * Gets the glow intensity.
  84568. */
  84569. get: function () {
  84570. return this._intensity;
  84571. },
  84572. /**
  84573. * Sets the glow intensity.
  84574. */
  84575. set: function (value) {
  84576. this._intensity = value;
  84577. },
  84578. enumerable: true,
  84579. configurable: true
  84580. });
  84581. /**
  84582. * Get the effect name of the layer.
  84583. * @return The effect name
  84584. */
  84585. GlowLayer.prototype.getEffectName = function () {
  84586. return GlowLayer.EffectName;
  84587. };
  84588. /**
  84589. * Create the merge effect. This is the shader use to blit the information back
  84590. * to the main canvas at the end of the scene rendering.
  84591. */
  84592. GlowLayer.prototype._createMergeEffect = function () {
  84593. // Effect
  84594. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84595. };
  84596. /**
  84597. * Creates the render target textures and post processes used in the glow layer.
  84598. */
  84599. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84600. var _this = this;
  84601. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84602. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84603. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84604. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84605. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84606. width: blurTextureWidth,
  84607. height: blurTextureHeight
  84608. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84609. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84610. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84611. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84612. this._blurTexture1.renderParticles = false;
  84613. this._blurTexture1.ignoreCameraViewport = true;
  84614. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84615. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84616. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84617. width: blurTextureWidth2,
  84618. height: blurTextureHeight2
  84619. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84620. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84621. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84622. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84623. this._blurTexture2.renderParticles = false;
  84624. this._blurTexture2.ignoreCameraViewport = true;
  84625. this._textures = [this._blurTexture1, this._blurTexture2];
  84626. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84627. width: blurTextureWidth,
  84628. height: blurTextureHeight
  84629. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84630. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84631. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84632. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84633. effect.setTexture("textureSampler", _this._mainTexture);
  84634. });
  84635. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84636. width: blurTextureWidth,
  84637. height: blurTextureHeight
  84638. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84639. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84640. width: blurTextureWidth2,
  84641. height: blurTextureHeight2
  84642. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84643. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84644. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84645. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84646. effect.setTexture("textureSampler", _this._blurTexture1);
  84647. });
  84648. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84649. width: blurTextureWidth2,
  84650. height: blurTextureHeight2
  84651. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84652. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84653. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84654. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84655. this._mainTexture.samples = this._options.mainTextureSamples;
  84656. this._mainTexture.onAfterUnbindObservable.add(function () {
  84657. var internalTexture = _this._blurTexture1.getInternalTexture();
  84658. if (internalTexture) {
  84659. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84660. internalTexture = _this._blurTexture2.getInternalTexture();
  84661. if (internalTexture) {
  84662. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84663. }
  84664. }
  84665. });
  84666. // Prevent autoClear.
  84667. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84668. };
  84669. /**
  84670. * Checks for the readiness of the element composing the layer.
  84671. * @param subMesh the mesh to check for
  84672. * @param useInstances specify wether or not to use instances to render the mesh
  84673. * @param emissiveTexture the associated emissive texture used to generate the glow
  84674. * @return true if ready otherwise, false
  84675. */
  84676. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84677. var material = subMesh.getMaterial();
  84678. var mesh = subMesh.getRenderingMesh();
  84679. if (!material || !mesh) {
  84680. return false;
  84681. }
  84682. var emissiveTexture = material.emissiveTexture;
  84683. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84684. };
  84685. /**
  84686. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84687. */
  84688. GlowLayer.prototype.needStencil = function () {
  84689. return false;
  84690. };
  84691. /**
  84692. * Implementation specific of rendering the generating effect on the main canvas.
  84693. * @param effect The effect used to render through
  84694. */
  84695. GlowLayer.prototype._internalRender = function (effect) {
  84696. // Texture
  84697. effect.setTexture("textureSampler", this._blurTexture1);
  84698. effect.setTexture("textureSampler2", this._blurTexture2);
  84699. effect.setFloat("offset", this._intensity);
  84700. // Cache
  84701. var engine = this._engine;
  84702. var previousStencilBuffer = engine.getStencilBuffer();
  84703. // Draw order
  84704. engine.setStencilBuffer(false);
  84705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84706. // Draw order
  84707. engine.setStencilBuffer(previousStencilBuffer);
  84708. };
  84709. /**
  84710. * Sets the required values for both the emissive texture and and the main color.
  84711. */
  84712. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84713. var textureLevel = 1.0;
  84714. if (this.customEmissiveTextureSelector) {
  84715. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84716. }
  84717. else {
  84718. if (material) {
  84719. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84720. if (this._emissiveTextureAndColor.texture) {
  84721. textureLevel = this._emissiveTextureAndColor.texture.level;
  84722. }
  84723. }
  84724. else {
  84725. this._emissiveTextureAndColor.texture = null;
  84726. }
  84727. }
  84728. if (this.customEmissiveColorSelector) {
  84729. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84730. }
  84731. else {
  84732. if (material.emissiveColor) {
  84733. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84734. }
  84735. else {
  84736. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84737. }
  84738. }
  84739. };
  84740. /**
  84741. * Returns true if the mesh should render, otherwise false.
  84742. * @param mesh The mesh to render
  84743. * @returns true if it should render otherwise false
  84744. */
  84745. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84746. return this.hasMesh(mesh);
  84747. };
  84748. /**
  84749. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84750. * @param mesh The mesh to exclude from the glow layer
  84751. */
  84752. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84753. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84754. this._excludedMeshes.push(mesh.uniqueId);
  84755. }
  84756. };
  84757. /**
  84758. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84759. * @param mesh The mesh to remove
  84760. */
  84761. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84762. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84763. if (index !== -1) {
  84764. this._excludedMeshes.splice(index, 1);
  84765. }
  84766. };
  84767. /**
  84768. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84769. * @param mesh The mesh to include in the glow layer
  84770. */
  84771. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84772. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84773. this._includedOnlyMeshes.push(mesh.uniqueId);
  84774. }
  84775. };
  84776. /**
  84777. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84778. * @param mesh The mesh to remove
  84779. */
  84780. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84781. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84782. if (index !== -1) {
  84783. this._includedOnlyMeshes.splice(index, 1);
  84784. }
  84785. };
  84786. /**
  84787. * Determine if a given mesh will be used in the glow layer
  84788. * @param mesh The mesh to test
  84789. * @returns true if the mesh will be highlighted by the current glow layer
  84790. */
  84791. GlowLayer.prototype.hasMesh = function (mesh) {
  84792. // Included Mesh
  84793. if (this._includedOnlyMeshes.length) {
  84794. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84795. }
  84796. ;
  84797. // Excluded Mesh
  84798. if (this._excludedMeshes.length) {
  84799. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84800. }
  84801. ;
  84802. return true;
  84803. };
  84804. /**
  84805. * Free any resources and references associated to a mesh.
  84806. * Internal use
  84807. * @param mesh The mesh to free.
  84808. */
  84809. GlowLayer.prototype._disposeMesh = function (mesh) {
  84810. this.removeIncludedOnlyMesh(mesh);
  84811. this.removeExcludedMesh(mesh);
  84812. };
  84813. /**
  84814. * Effect Name of the layer.
  84815. */
  84816. GlowLayer.EffectName = "GlowLayer";
  84817. /**
  84818. * The default blur kernel size used for the glow.
  84819. */
  84820. GlowLayer.DefaultBlurKernelSize = 32;
  84821. /**
  84822. * The default texture size ratio used for the glow.
  84823. */
  84824. GlowLayer.DefaultTextureRatio = 0.5;
  84825. return GlowLayer;
  84826. }(BABYLON.EffectLayer));
  84827. BABYLON.GlowLayer = GlowLayer;
  84828. })(BABYLON || (BABYLON = {}));
  84829. //# sourceMappingURL=babylon.glowLayer.js.map
  84830. var BABYLON;
  84831. (function (BABYLON) {
  84832. /**
  84833. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84834. */
  84835. var AssetTaskState;
  84836. (function (AssetTaskState) {
  84837. /**
  84838. * Initialization
  84839. */
  84840. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84841. /**
  84842. * Running
  84843. */
  84844. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84845. /**
  84846. * Done
  84847. */
  84848. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84849. /**
  84850. * Error
  84851. */
  84852. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84853. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84854. /**
  84855. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84856. */
  84857. var AbstractAssetTask = /** @class */ (function () {
  84858. /**
  84859. * Creates a new {BABYLON.AssetsManager}
  84860. * @param name defines the name of the task
  84861. */
  84862. function AbstractAssetTask(
  84863. /**
  84864. * Task name
  84865. */ name) {
  84866. this.name = name;
  84867. this._isCompleted = false;
  84868. this._taskState = AssetTaskState.INIT;
  84869. }
  84870. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84871. /**
  84872. * Get if the task is completed
  84873. */
  84874. get: function () {
  84875. return this._isCompleted;
  84876. },
  84877. enumerable: true,
  84878. configurable: true
  84879. });
  84880. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84881. /**
  84882. * Gets the current state of the task
  84883. */
  84884. get: function () {
  84885. return this._taskState;
  84886. },
  84887. enumerable: true,
  84888. configurable: true
  84889. });
  84890. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84891. /**
  84892. * Gets the current error object (if task is in error)
  84893. */
  84894. get: function () {
  84895. return this._errorObject;
  84896. },
  84897. enumerable: true,
  84898. configurable: true
  84899. });
  84900. /**
  84901. * Internal only
  84902. * @ignore
  84903. */
  84904. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84905. if (this._errorObject) {
  84906. return;
  84907. }
  84908. this._errorObject = {
  84909. message: message,
  84910. exception: exception
  84911. };
  84912. };
  84913. /**
  84914. * Execute the current task
  84915. * @param scene defines the scene where you want your assets to be loaded
  84916. * @param onSuccess is a callback called when the task is successfully executed
  84917. * @param onError is a callback called if an error occurs
  84918. */
  84919. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84920. var _this = this;
  84921. this._taskState = AssetTaskState.RUNNING;
  84922. this.runTask(scene, function () {
  84923. _this.onDoneCallback(onSuccess, onError);
  84924. }, function (msg, exception) {
  84925. _this.onErrorCallback(onError, msg, exception);
  84926. });
  84927. };
  84928. /**
  84929. * Execute the current task
  84930. * @param scene defines the scene where you want your assets to be loaded
  84931. * @param onSuccess is a callback called when the task is successfully executed
  84932. * @param onError is a callback called if an error occurs
  84933. */
  84934. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84935. throw new Error("runTask is not implemented");
  84936. };
  84937. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84938. this._taskState = AssetTaskState.ERROR;
  84939. this._errorObject = {
  84940. message: message,
  84941. exception: exception
  84942. };
  84943. if (this.onError) {
  84944. this.onError(this, message, exception);
  84945. }
  84946. onError();
  84947. };
  84948. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  84949. try {
  84950. this._taskState = AssetTaskState.DONE;
  84951. this._isCompleted = true;
  84952. if (this.onSuccess) {
  84953. this.onSuccess(this);
  84954. }
  84955. onSuccess();
  84956. }
  84957. catch (e) {
  84958. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  84959. }
  84960. };
  84961. return AbstractAssetTask;
  84962. }());
  84963. BABYLON.AbstractAssetTask = AbstractAssetTask;
  84964. /**
  84965. * Class used to share progress information about assets loading
  84966. */
  84967. var AssetsProgressEvent = /** @class */ (function () {
  84968. /**
  84969. * Creates a {BABYLON.AssetsProgressEvent}
  84970. * @param remainingCount defines the number of remaining tasks to process
  84971. * @param totalCount defines the total number of tasks
  84972. * @param task defines the task that was just processed
  84973. */
  84974. function AssetsProgressEvent(remainingCount, totalCount, task) {
  84975. this.remainingCount = remainingCount;
  84976. this.totalCount = totalCount;
  84977. this.task = task;
  84978. }
  84979. return AssetsProgressEvent;
  84980. }());
  84981. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  84982. /**
  84983. * Define a task used by {BABYLON.AssetsManager} to load meshes
  84984. */
  84985. var MeshAssetTask = /** @class */ (function (_super) {
  84986. __extends(MeshAssetTask, _super);
  84987. /**
  84988. * Creates a new {BABYLON.MeshAssetTask}
  84989. * @param name defines the name of the task
  84990. * @param meshesNames defines the list of mesh's names you want to load
  84991. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  84992. * @param sceneFilename defines the filename of the scene to load from
  84993. */
  84994. function MeshAssetTask(
  84995. /**
  84996. * Defines the name of the task
  84997. */
  84998. name,
  84999. /**
  85000. * Defines the list of mesh's names you want to load
  85001. */
  85002. meshesNames,
  85003. /**
  85004. * Defines the root url to use as a base to load your meshes and associated resources
  85005. */
  85006. rootUrl,
  85007. /**
  85008. * Defines the filename of the scene to load from
  85009. */
  85010. sceneFilename) {
  85011. var _this = _super.call(this, name) || this;
  85012. _this.name = name;
  85013. _this.meshesNames = meshesNames;
  85014. _this.rootUrl = rootUrl;
  85015. _this.sceneFilename = sceneFilename;
  85016. return _this;
  85017. }
  85018. /**
  85019. * Execute the current task
  85020. * @param scene defines the scene where you want your assets to be loaded
  85021. * @param onSuccess is a callback called when the task is successfully executed
  85022. * @param onError is a callback called if an error occurs
  85023. */
  85024. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85025. var _this = this;
  85026. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85027. _this.loadedMeshes = meshes;
  85028. _this.loadedParticleSystems = particleSystems;
  85029. _this.loadedSkeletons = skeletons;
  85030. onSuccess();
  85031. }, null, function (scene, message, exception) {
  85032. onError(message, exception);
  85033. });
  85034. };
  85035. return MeshAssetTask;
  85036. }(AbstractAssetTask));
  85037. BABYLON.MeshAssetTask = MeshAssetTask;
  85038. /**
  85039. * Define a task used by {BABYLON.AssetsManager} to load text content
  85040. */
  85041. var TextFileAssetTask = /** @class */ (function (_super) {
  85042. __extends(TextFileAssetTask, _super);
  85043. /**
  85044. * Creates a new TextFileAssetTask object
  85045. * @param name defines the name of the task
  85046. * @param url defines the location of the file to load
  85047. */
  85048. function TextFileAssetTask(
  85049. /**
  85050. * Defines the name of the task
  85051. */
  85052. name,
  85053. /**
  85054. * Defines the location of the file to load
  85055. */
  85056. url) {
  85057. var _this = _super.call(this, name) || this;
  85058. _this.name = name;
  85059. _this.url = url;
  85060. return _this;
  85061. }
  85062. /**
  85063. * Execute the current task
  85064. * @param scene defines the scene where you want your assets to be loaded
  85065. * @param onSuccess is a callback called when the task is successfully executed
  85066. * @param onError is a callback called if an error occurs
  85067. */
  85068. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85069. var _this = this;
  85070. scene._loadFile(this.url, function (data) {
  85071. _this.text = data;
  85072. onSuccess();
  85073. }, undefined, false, false, function (request, exception) {
  85074. if (request) {
  85075. onError(request.status + " " + request.statusText, exception);
  85076. }
  85077. });
  85078. };
  85079. return TextFileAssetTask;
  85080. }(AbstractAssetTask));
  85081. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85082. /**
  85083. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85084. */
  85085. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85086. __extends(BinaryFileAssetTask, _super);
  85087. /**
  85088. * Creates a new BinaryFileAssetTask object
  85089. * @param name defines the name of the new task
  85090. * @param url defines the location of the file to load
  85091. */
  85092. function BinaryFileAssetTask(
  85093. /**
  85094. * Defines the name of the task
  85095. */
  85096. name,
  85097. /**
  85098. * Defines the location of the file to load
  85099. */
  85100. url) {
  85101. var _this = _super.call(this, name) || this;
  85102. _this.name = name;
  85103. _this.url = url;
  85104. return _this;
  85105. }
  85106. /**
  85107. * Execute the current task
  85108. * @param scene defines the scene where you want your assets to be loaded
  85109. * @param onSuccess is a callback called when the task is successfully executed
  85110. * @param onError is a callback called if an error occurs
  85111. */
  85112. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85113. var _this = this;
  85114. scene._loadFile(this.url, function (data) {
  85115. _this.data = data;
  85116. onSuccess();
  85117. }, undefined, true, true, function (request, exception) {
  85118. if (request) {
  85119. onError(request.status + " " + request.statusText, exception);
  85120. }
  85121. });
  85122. };
  85123. return BinaryFileAssetTask;
  85124. }(AbstractAssetTask));
  85125. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85126. /**
  85127. * Define a task used by {BABYLON.AssetsManager} to load images
  85128. */
  85129. var ImageAssetTask = /** @class */ (function (_super) {
  85130. __extends(ImageAssetTask, _super);
  85131. /**
  85132. * Creates a new ImageAssetTask
  85133. * @param name defines the name of the task
  85134. * @param url defines the location of the image to load
  85135. */
  85136. function ImageAssetTask(
  85137. /**
  85138. * Defines the name of the task
  85139. */
  85140. name,
  85141. /**
  85142. * Defines the location of the image to load
  85143. */
  85144. url) {
  85145. var _this = _super.call(this, name) || this;
  85146. _this.name = name;
  85147. _this.url = url;
  85148. return _this;
  85149. }
  85150. /**
  85151. * Execute the current task
  85152. * @param scene defines the scene where you want your assets to be loaded
  85153. * @param onSuccess is a callback called when the task is successfully executed
  85154. * @param onError is a callback called if an error occurs
  85155. */
  85156. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85157. var _this = this;
  85158. var img = new Image();
  85159. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85160. img.onload = function () {
  85161. _this.image = img;
  85162. onSuccess();
  85163. };
  85164. img.onerror = function (err) {
  85165. onError("Error loading image", err);
  85166. };
  85167. img.src = this.url;
  85168. };
  85169. return ImageAssetTask;
  85170. }(AbstractAssetTask));
  85171. BABYLON.ImageAssetTask = ImageAssetTask;
  85172. /**
  85173. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85174. */
  85175. var TextureAssetTask = /** @class */ (function (_super) {
  85176. __extends(TextureAssetTask, _super);
  85177. /**
  85178. * Creates a new TextureAssetTask object
  85179. * @param name defines the name of the task
  85180. * @param url defines the location of the file to load
  85181. * @param noMipmap defines if mipmap should not be generated (default is false)
  85182. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85183. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85184. */
  85185. function TextureAssetTask(
  85186. /**
  85187. * Defines the name of the task
  85188. */
  85189. name,
  85190. /**
  85191. * Defines the location of the file to load
  85192. */
  85193. url,
  85194. /**
  85195. * Defines if mipmap should not be generated (default is false)
  85196. */
  85197. noMipmap,
  85198. /**
  85199. * Defines if texture must be inverted on Y axis (default is false)
  85200. */
  85201. invertY,
  85202. /**
  85203. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85204. */
  85205. samplingMode) {
  85206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85207. var _this = _super.call(this, name) || this;
  85208. _this.name = name;
  85209. _this.url = url;
  85210. _this.noMipmap = noMipmap;
  85211. _this.invertY = invertY;
  85212. _this.samplingMode = samplingMode;
  85213. return _this;
  85214. }
  85215. /**
  85216. * Execute the current task
  85217. * @param scene defines the scene where you want your assets to be loaded
  85218. * @param onSuccess is a callback called when the task is successfully executed
  85219. * @param onError is a callback called if an error occurs
  85220. */
  85221. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85222. var onload = function () {
  85223. onSuccess();
  85224. };
  85225. var onerror = function (message, exception) {
  85226. onError(message, exception);
  85227. };
  85228. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85229. };
  85230. return TextureAssetTask;
  85231. }(AbstractAssetTask));
  85232. BABYLON.TextureAssetTask = TextureAssetTask;
  85233. /**
  85234. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85235. */
  85236. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85237. __extends(CubeTextureAssetTask, _super);
  85238. /**
  85239. * Creates a new CubeTextureAssetTask
  85240. * @param name defines the name of the task
  85241. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85242. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85243. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85244. * @param files defines the explicit list of files (undefined by default)
  85245. */
  85246. function CubeTextureAssetTask(
  85247. /**
  85248. * Defines the name of the task
  85249. */
  85250. name,
  85251. /**
  85252. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85253. */
  85254. url,
  85255. /**
  85256. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85257. */
  85258. extensions,
  85259. /**
  85260. * Defines if mipmaps should not be generated (default is false)
  85261. */
  85262. noMipmap,
  85263. /**
  85264. * Defines the explicit list of files (undefined by default)
  85265. */
  85266. files) {
  85267. var _this = _super.call(this, name) || this;
  85268. _this.name = name;
  85269. _this.url = url;
  85270. _this.extensions = extensions;
  85271. _this.noMipmap = noMipmap;
  85272. _this.files = files;
  85273. return _this;
  85274. }
  85275. /**
  85276. * Execute the current task
  85277. * @param scene defines the scene where you want your assets to be loaded
  85278. * @param onSuccess is a callback called when the task is successfully executed
  85279. * @param onError is a callback called if an error occurs
  85280. */
  85281. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85282. var onload = function () {
  85283. onSuccess();
  85284. };
  85285. var onerror = function (message, exception) {
  85286. onError(message, exception);
  85287. };
  85288. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85289. };
  85290. return CubeTextureAssetTask;
  85291. }(AbstractAssetTask));
  85292. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85293. /**
  85294. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85295. */
  85296. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85297. __extends(HDRCubeTextureAssetTask, _super);
  85298. /**
  85299. * Creates a new HDRCubeTextureAssetTask object
  85300. * @param name defines the name of the task
  85301. * @param url defines the location of the file to load
  85302. * @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.
  85303. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85304. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85305. * @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)
  85306. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85307. */
  85308. function HDRCubeTextureAssetTask(
  85309. /**
  85310. * Defines the name of the task
  85311. */
  85312. name,
  85313. /**
  85314. * Defines the location of the file to load
  85315. */
  85316. url,
  85317. /**
  85318. * 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.
  85319. */
  85320. size,
  85321. /**
  85322. * Defines if mipmaps should not be generated (default is false)
  85323. */
  85324. noMipmap,
  85325. /**
  85326. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85327. */
  85328. generateHarmonics,
  85329. /**
  85330. * 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)
  85331. */
  85332. useInGammaSpace,
  85333. /**
  85334. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85335. */
  85336. usePMREMGenerator) {
  85337. if (noMipmap === void 0) { noMipmap = false; }
  85338. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85339. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85340. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85341. var _this = _super.call(this, name) || this;
  85342. _this.name = name;
  85343. _this.url = url;
  85344. _this.size = size;
  85345. _this.noMipmap = noMipmap;
  85346. _this.generateHarmonics = generateHarmonics;
  85347. _this.useInGammaSpace = useInGammaSpace;
  85348. _this.usePMREMGenerator = usePMREMGenerator;
  85349. return _this;
  85350. }
  85351. /**
  85352. * Execute the current task
  85353. * @param scene defines the scene where you want your assets to be loaded
  85354. * @param onSuccess is a callback called when the task is successfully executed
  85355. * @param onError is a callback called if an error occurs
  85356. */
  85357. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85358. var onload = function () {
  85359. onSuccess();
  85360. };
  85361. var onerror = function (message, exception) {
  85362. onError(message, exception);
  85363. };
  85364. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85365. };
  85366. return HDRCubeTextureAssetTask;
  85367. }(AbstractAssetTask));
  85368. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85369. /**
  85370. * This class can be used to easily import assets into a scene
  85371. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85372. */
  85373. var AssetsManager = /** @class */ (function () {
  85374. /**
  85375. * Creates a new AssetsManager
  85376. * @param scene defines the scene to work on
  85377. */
  85378. function AssetsManager(scene) {
  85379. this._isLoading = false;
  85380. this._tasks = new Array();
  85381. this._waitingTasksCount = 0;
  85382. this._totalTasksCount = 0;
  85383. /**
  85384. * Observable called when all tasks are processed
  85385. */
  85386. this.onTaskSuccessObservable = new BABYLON.Observable();
  85387. /**
  85388. * Observable called when a task had an error
  85389. */
  85390. this.onTaskErrorObservable = new BABYLON.Observable();
  85391. /**
  85392. * Observable called when a task is successful
  85393. */
  85394. this.onTasksDoneObservable = new BABYLON.Observable();
  85395. /**
  85396. * Observable called when a task is done (whatever the result is)
  85397. */
  85398. this.onProgressObservable = new BABYLON.Observable();
  85399. /**
  85400. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85401. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85402. */
  85403. this.useDefaultLoadingScreen = true;
  85404. this._scene = scene;
  85405. }
  85406. /**
  85407. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85408. * @param taskName defines the name of the new task
  85409. * @param meshesNames defines the name of meshes to load
  85410. * @param rootUrl defines the root url to use to locate files
  85411. * @param sceneFilename defines the filename of the scene file
  85412. * @returns a new {BABYLON.MeshAssetTask} object
  85413. */
  85414. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85415. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85416. this._tasks.push(task);
  85417. return task;
  85418. };
  85419. /**
  85420. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85421. * @param taskName defines the name of the new task
  85422. * @param url defines the url of the file to load
  85423. * @returns a new {BABYLON.TextFileAssetTask} object
  85424. */
  85425. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85426. var task = new TextFileAssetTask(taskName, url);
  85427. this._tasks.push(task);
  85428. return task;
  85429. };
  85430. /**
  85431. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85432. * @param taskName defines the name of the new task
  85433. * @param url defines the url of the file to load
  85434. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85435. */
  85436. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85437. var task = new BinaryFileAssetTask(taskName, url);
  85438. this._tasks.push(task);
  85439. return task;
  85440. };
  85441. /**
  85442. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85443. * @param taskName defines the name of the new task
  85444. * @param url defines the url of the file to load
  85445. * @returns a new {BABYLON.ImageAssetTask} object
  85446. */
  85447. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85448. var task = new ImageAssetTask(taskName, url);
  85449. this._tasks.push(task);
  85450. return task;
  85451. };
  85452. /**
  85453. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85454. * @param taskName defines the name of the new task
  85455. * @param url defines the url of the file to load
  85456. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85457. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85458. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85459. * @returns a new {BABYLON.TextureAssetTask} object
  85460. */
  85461. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85463. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85464. this._tasks.push(task);
  85465. return task;
  85466. };
  85467. /**
  85468. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85469. * @param taskName defines the name of the new task
  85470. * @param url defines the url of the file to load
  85471. * @param extensions defines the extension to use to load the cube map (can be null)
  85472. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85473. * @param files defines the list of files to load (can be null)
  85474. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85475. */
  85476. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85477. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85478. this._tasks.push(task);
  85479. return task;
  85480. };
  85481. /**
  85482. *
  85483. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85484. * @param taskName defines the name of the new task
  85485. * @param url defines the url of the file to load
  85486. * @param size defines the size you want for the cubemap (can be null)
  85487. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85488. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85489. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85490. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85491. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85492. */
  85493. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85494. if (noMipmap === void 0) { noMipmap = false; }
  85495. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85496. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85497. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85498. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85499. this._tasks.push(task);
  85500. return task;
  85501. };
  85502. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85503. var _this = this;
  85504. this._waitingTasksCount--;
  85505. try {
  85506. if (task.taskState === AssetTaskState.DONE) {
  85507. // Let's remove successfull tasks
  85508. BABYLON.Tools.SetImmediate(function () {
  85509. var index = _this._tasks.indexOf(task);
  85510. if (index > -1) {
  85511. _this._tasks.splice(index, 1);
  85512. }
  85513. });
  85514. }
  85515. if (this.onProgress) {
  85516. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85517. }
  85518. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85519. }
  85520. catch (e) {
  85521. BABYLON.Tools.Error("Error running progress callbacks.");
  85522. console.log(e);
  85523. }
  85524. if (this._waitingTasksCount === 0) {
  85525. try {
  85526. if (this.onFinish) {
  85527. this.onFinish(this._tasks);
  85528. }
  85529. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85530. }
  85531. catch (e) {
  85532. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85533. console.log(e);
  85534. }
  85535. this._isLoading = false;
  85536. this._scene.getEngine().hideLoadingUI();
  85537. }
  85538. };
  85539. AssetsManager.prototype._runTask = function (task) {
  85540. var _this = this;
  85541. var done = function () {
  85542. try {
  85543. if (_this.onTaskSuccess) {
  85544. _this.onTaskSuccess(task);
  85545. }
  85546. _this.onTaskSuccessObservable.notifyObservers(task);
  85547. _this._decreaseWaitingTasksCount(task);
  85548. }
  85549. catch (e) {
  85550. error("Error executing task success callbacks", e);
  85551. }
  85552. };
  85553. var error = function (message, exception) {
  85554. task._setErrorObject(message, exception);
  85555. if (_this.onTaskError) {
  85556. _this.onTaskError(task);
  85557. }
  85558. _this.onTaskErrorObservable.notifyObservers(task);
  85559. _this._decreaseWaitingTasksCount(task);
  85560. };
  85561. task.run(this._scene, done, error);
  85562. };
  85563. /**
  85564. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85565. * @return the current instance of the {BABYLON.AssetsManager}
  85566. */
  85567. AssetsManager.prototype.reset = function () {
  85568. this._isLoading = false;
  85569. this._tasks = new Array();
  85570. return this;
  85571. };
  85572. /**
  85573. * Start the loading process
  85574. * @return the current instance of the {BABYLON.AssetsManager}
  85575. */
  85576. AssetsManager.prototype.load = function () {
  85577. if (this._isLoading) {
  85578. return this;
  85579. }
  85580. this._isLoading = true;
  85581. this._waitingTasksCount = this._tasks.length;
  85582. this._totalTasksCount = this._tasks.length;
  85583. if (this._waitingTasksCount === 0) {
  85584. this._isLoading = false;
  85585. if (this.onFinish) {
  85586. this.onFinish(this._tasks);
  85587. }
  85588. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85589. return this;
  85590. }
  85591. if (this.useDefaultLoadingScreen) {
  85592. this._scene.getEngine().displayLoadingUI();
  85593. }
  85594. for (var index = 0; index < this._tasks.length; index++) {
  85595. var task = this._tasks[index];
  85596. this._runTask(task);
  85597. }
  85598. return this;
  85599. };
  85600. return AssetsManager;
  85601. }());
  85602. BABYLON.AssetsManager = AssetsManager;
  85603. })(BABYLON || (BABYLON = {}));
  85604. //# sourceMappingURL=babylon.assetsManager.js.map
  85605. var BABYLON;
  85606. (function (BABYLON) {
  85607. var serializedGeometries = [];
  85608. var serializeGeometry = function (geometry, serializationGeometries) {
  85609. if (serializedGeometries[geometry.id]) {
  85610. return;
  85611. }
  85612. if (geometry.doNotSerialize) {
  85613. return;
  85614. }
  85615. if (geometry instanceof BABYLON.BoxGeometry) {
  85616. serializationGeometries.boxes.push(geometry.serialize());
  85617. }
  85618. else if (geometry instanceof BABYLON.SphereGeometry) {
  85619. serializationGeometries.spheres.push(geometry.serialize());
  85620. }
  85621. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85622. serializationGeometries.cylinders.push(geometry.serialize());
  85623. }
  85624. else if (geometry instanceof BABYLON.TorusGeometry) {
  85625. serializationGeometries.toruses.push(geometry.serialize());
  85626. }
  85627. else if (geometry instanceof BABYLON.GroundGeometry) {
  85628. serializationGeometries.grounds.push(geometry.serialize());
  85629. }
  85630. else if (geometry instanceof BABYLON.Plane) {
  85631. serializationGeometries.planes.push(geometry.serialize());
  85632. }
  85633. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85634. serializationGeometries.torusKnots.push(geometry.serialize());
  85635. }
  85636. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85637. throw new Error("Unknown primitive type");
  85638. }
  85639. else {
  85640. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85641. }
  85642. serializedGeometries[geometry.id] = true;
  85643. };
  85644. var serializeMesh = function (mesh, serializationScene) {
  85645. var serializationObject = {};
  85646. // Geometry
  85647. var geometry = mesh._geometry;
  85648. if (geometry) {
  85649. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85650. // 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
  85651. serializeGeometry(geometry, serializationScene.geometries);
  85652. }
  85653. }
  85654. // Custom
  85655. if (mesh.serialize) {
  85656. mesh.serialize(serializationObject);
  85657. }
  85658. return serializationObject;
  85659. };
  85660. var finalizeSingleMesh = function (mesh, serializationObject) {
  85661. //only works if the mesh is already loaded
  85662. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85663. //serialize material
  85664. if (mesh.material) {
  85665. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85666. serializationObject.materials = serializationObject.materials || [];
  85667. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85668. serializationObject.materials.push(mesh.material.serialize());
  85669. }
  85670. }
  85671. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85672. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85673. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85674. serializationObject.multiMaterials.push(mesh.material.serialize());
  85675. }
  85676. }
  85677. }
  85678. //serialize geometry
  85679. var geometry = mesh._geometry;
  85680. if (geometry) {
  85681. if (!serializationObject.geometries) {
  85682. serializationObject.geometries = {};
  85683. serializationObject.geometries.boxes = [];
  85684. serializationObject.geometries.spheres = [];
  85685. serializationObject.geometries.cylinders = [];
  85686. serializationObject.geometries.toruses = [];
  85687. serializationObject.geometries.grounds = [];
  85688. serializationObject.geometries.planes = [];
  85689. serializationObject.geometries.torusKnots = [];
  85690. serializationObject.geometries.vertexData = [];
  85691. }
  85692. serializeGeometry(geometry, serializationObject.geometries);
  85693. }
  85694. // Skeletons
  85695. if (mesh.skeleton) {
  85696. serializationObject.skeletons = serializationObject.skeletons || [];
  85697. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85698. }
  85699. //serialize the actual mesh
  85700. serializationObject.meshes = serializationObject.meshes || [];
  85701. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85702. }
  85703. };
  85704. var SceneSerializer = /** @class */ (function () {
  85705. function SceneSerializer() {
  85706. }
  85707. SceneSerializer.ClearCache = function () {
  85708. serializedGeometries = [];
  85709. };
  85710. SceneSerializer.Serialize = function (scene) {
  85711. var serializationObject = {};
  85712. SceneSerializer.ClearCache();
  85713. // Scene
  85714. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85715. serializationObject.autoClear = scene.autoClear;
  85716. serializationObject.clearColor = scene.clearColor.asArray();
  85717. serializationObject.ambientColor = scene.ambientColor.asArray();
  85718. serializationObject.gravity = scene.gravity.asArray();
  85719. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85720. serializationObject.workerCollisions = scene.workerCollisions;
  85721. // Fog
  85722. if (scene.fogMode && scene.fogMode !== 0) {
  85723. serializationObject.fogMode = scene.fogMode;
  85724. serializationObject.fogColor = scene.fogColor.asArray();
  85725. serializationObject.fogStart = scene.fogStart;
  85726. serializationObject.fogEnd = scene.fogEnd;
  85727. serializationObject.fogDensity = scene.fogDensity;
  85728. }
  85729. //Physics
  85730. if (scene.isPhysicsEnabled()) {
  85731. var physicEngine = scene.getPhysicsEngine();
  85732. if (physicEngine) {
  85733. serializationObject.physicsEnabled = true;
  85734. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85735. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85736. }
  85737. }
  85738. // Metadata
  85739. if (scene.metadata) {
  85740. serializationObject.metadata = scene.metadata;
  85741. }
  85742. // Morph targets
  85743. serializationObject.morphTargetManagers = [];
  85744. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85745. var abstractMesh = _a[_i];
  85746. var manager = abstractMesh.morphTargetManager;
  85747. if (manager) {
  85748. serializationObject.morphTargetManagers.push(manager.serialize());
  85749. }
  85750. }
  85751. // Lights
  85752. serializationObject.lights = [];
  85753. var index;
  85754. var light;
  85755. for (index = 0; index < scene.lights.length; index++) {
  85756. light = scene.lights[index];
  85757. if (!light.doNotSerialize) {
  85758. serializationObject.lights.push(light.serialize());
  85759. }
  85760. }
  85761. // Cameras
  85762. serializationObject.cameras = [];
  85763. for (index = 0; index < scene.cameras.length; index++) {
  85764. var camera = scene.cameras[index];
  85765. if (!camera.doNotSerialize) {
  85766. serializationObject.cameras.push(camera.serialize());
  85767. }
  85768. }
  85769. if (scene.activeCamera) {
  85770. serializationObject.activeCameraID = scene.activeCamera.id;
  85771. }
  85772. // Animations
  85773. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85774. // Materials
  85775. serializationObject.materials = [];
  85776. serializationObject.multiMaterials = [];
  85777. var material;
  85778. for (index = 0; index < scene.materials.length; index++) {
  85779. material = scene.materials[index];
  85780. if (!material.doNotSerialize) {
  85781. serializationObject.materials.push(material.serialize());
  85782. }
  85783. }
  85784. // MultiMaterials
  85785. serializationObject.multiMaterials = [];
  85786. for (index = 0; index < scene.multiMaterials.length; index++) {
  85787. var multiMaterial = scene.multiMaterials[index];
  85788. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85789. }
  85790. // Environment texture
  85791. if (scene.environmentTexture) {
  85792. serializationObject.environmentTexture = scene.environmentTexture.name;
  85793. }
  85794. // Skeletons
  85795. serializationObject.skeletons = [];
  85796. for (index = 0; index < scene.skeletons.length; index++) {
  85797. var skeleton = scene.skeletons[index];
  85798. if (!skeleton.doNotSerialize) {
  85799. serializationObject.skeletons.push(skeleton.serialize());
  85800. }
  85801. }
  85802. // Transform nodes
  85803. serializationObject.transformNodes = [];
  85804. for (index = 0; index < scene.transformNodes.length; index++) {
  85805. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85806. }
  85807. // Geometries
  85808. serializationObject.geometries = {};
  85809. serializationObject.geometries.boxes = [];
  85810. serializationObject.geometries.spheres = [];
  85811. serializationObject.geometries.cylinders = [];
  85812. serializationObject.geometries.toruses = [];
  85813. serializationObject.geometries.grounds = [];
  85814. serializationObject.geometries.planes = [];
  85815. serializationObject.geometries.torusKnots = [];
  85816. serializationObject.geometries.vertexData = [];
  85817. serializedGeometries = [];
  85818. var geometries = scene.getGeometries();
  85819. for (index = 0; index < geometries.length; index++) {
  85820. var geometry = geometries[index];
  85821. if (geometry.isReady()) {
  85822. serializeGeometry(geometry, serializationObject.geometries);
  85823. }
  85824. }
  85825. // Meshes
  85826. serializationObject.meshes = [];
  85827. for (index = 0; index < scene.meshes.length; index++) {
  85828. var abstractMesh = scene.meshes[index];
  85829. if (abstractMesh instanceof BABYLON.Mesh) {
  85830. var mesh = abstractMesh;
  85831. if (!mesh.doNotSerialize) {
  85832. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85833. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85834. }
  85835. }
  85836. }
  85837. }
  85838. // Particles Systems
  85839. serializationObject.particleSystems = [];
  85840. for (index = 0; index < scene.particleSystems.length; index++) {
  85841. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85842. }
  85843. // Lens flares
  85844. serializationObject.lensFlareSystems = [];
  85845. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85846. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85847. }
  85848. // Shadows
  85849. serializationObject.shadowGenerators = [];
  85850. for (index = 0; index < scene.lights.length; index++) {
  85851. light = scene.lights[index];
  85852. var shadowGenerator = light.getShadowGenerator();
  85853. if (shadowGenerator) {
  85854. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85855. }
  85856. }
  85857. // Action Manager
  85858. if (scene.actionManager) {
  85859. serializationObject.actions = scene.actionManager.serialize("scene");
  85860. }
  85861. // Audio
  85862. serializationObject.sounds = [];
  85863. for (index = 0; index < scene.soundTracks.length; index++) {
  85864. var soundtrack = scene.soundTracks[index];
  85865. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85866. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85867. }
  85868. }
  85869. return serializationObject;
  85870. };
  85871. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85872. if (withParents === void 0) { withParents = false; }
  85873. if (withChildren === void 0) { withChildren = false; }
  85874. var serializationObject = {};
  85875. SceneSerializer.ClearCache();
  85876. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85877. if (withParents || withChildren) {
  85878. //deliberate for loop! not for each, appended should be processed as well.
  85879. for (var i = 0; i < toSerialize.length; ++i) {
  85880. if (withChildren) {
  85881. toSerialize[i].getDescendants().forEach(function (node) {
  85882. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85883. toSerialize.push(node);
  85884. }
  85885. });
  85886. }
  85887. //make sure the array doesn't contain the object already
  85888. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85889. toSerialize.push(toSerialize[i].parent);
  85890. }
  85891. }
  85892. }
  85893. toSerialize.forEach(function (mesh) {
  85894. finalizeSingleMesh(mesh, serializationObject);
  85895. });
  85896. return serializationObject;
  85897. };
  85898. return SceneSerializer;
  85899. }());
  85900. BABYLON.SceneSerializer = SceneSerializer;
  85901. })(BABYLON || (BABYLON = {}));
  85902. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85903. var BABYLON;
  85904. (function (BABYLON) {
  85905. var ReflectionProbe = /** @class */ (function () {
  85906. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85907. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85908. var _this = this;
  85909. this.name = name;
  85910. this._viewMatrix = BABYLON.Matrix.Identity();
  85911. this._target = BABYLON.Vector3.Zero();
  85912. this._add = BABYLON.Vector3.Zero();
  85913. this._invertYAxis = false;
  85914. this.position = BABYLON.Vector3.Zero();
  85915. this._scene = scene;
  85916. this._scene.reflectionProbes.push(this);
  85917. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85918. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85919. switch (faceIndex) {
  85920. case 0:
  85921. _this._add.copyFromFloats(1, 0, 0);
  85922. break;
  85923. case 1:
  85924. _this._add.copyFromFloats(-1, 0, 0);
  85925. break;
  85926. case 2:
  85927. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  85928. break;
  85929. case 3:
  85930. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  85931. break;
  85932. case 4:
  85933. _this._add.copyFromFloats(0, 0, 1);
  85934. break;
  85935. case 5:
  85936. _this._add.copyFromFloats(0, 0, -1);
  85937. break;
  85938. }
  85939. if (_this._attachedMesh) {
  85940. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85941. }
  85942. _this.position.addToRef(_this._add, _this._target);
  85943. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  85944. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  85945. scene._forcedViewPosition = _this.position;
  85946. });
  85947. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  85948. scene._forcedViewPosition = null;
  85949. scene.updateTransformMatrix(true);
  85950. });
  85951. if (scene.activeCamera) {
  85952. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85953. }
  85954. }
  85955. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  85956. get: function () {
  85957. return this._renderTargetTexture.samples;
  85958. },
  85959. set: function (value) {
  85960. this._renderTargetTexture.samples = value;
  85961. },
  85962. enumerable: true,
  85963. configurable: true
  85964. });
  85965. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  85966. get: function () {
  85967. return this._renderTargetTexture.refreshRate;
  85968. },
  85969. set: function (value) {
  85970. this._renderTargetTexture.refreshRate = value;
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. ReflectionProbe.prototype.getScene = function () {
  85976. return this._scene;
  85977. };
  85978. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  85979. get: function () {
  85980. return this._renderTargetTexture;
  85981. },
  85982. enumerable: true,
  85983. configurable: true
  85984. });
  85985. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  85986. get: function () {
  85987. return this._renderTargetTexture.renderList;
  85988. },
  85989. enumerable: true,
  85990. configurable: true
  85991. });
  85992. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  85993. this._attachedMesh = mesh;
  85994. };
  85995. /**
  85996. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  85997. *
  85998. * @param renderingGroupId The rendering group id corresponding to its index
  85999. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86000. */
  86001. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86002. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86003. };
  86004. ReflectionProbe.prototype.dispose = function () {
  86005. var index = this._scene.reflectionProbes.indexOf(this);
  86006. if (index !== -1) {
  86007. // Remove from the scene if found
  86008. this._scene.reflectionProbes.splice(index, 1);
  86009. }
  86010. if (this._renderTargetTexture) {
  86011. this._renderTargetTexture.dispose();
  86012. this._renderTargetTexture = null;
  86013. }
  86014. };
  86015. return ReflectionProbe;
  86016. }());
  86017. BABYLON.ReflectionProbe = ReflectionProbe;
  86018. })(BABYLON || (BABYLON = {}));
  86019. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86020. var BABYLON;
  86021. (function (BABYLON) {
  86022. var Layer = /** @class */ (function () {
  86023. function Layer(name, imgUrl, scene, isBackground, color) {
  86024. this.name = name;
  86025. this.scale = new BABYLON.Vector2(1, 1);
  86026. this.offset = new BABYLON.Vector2(0, 0);
  86027. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86028. this.layerMask = 0x0FFFFFFF;
  86029. this._vertexBuffers = {};
  86030. // Events
  86031. /**
  86032. * An event triggered when the layer is disposed.
  86033. * @type {BABYLON.Observable}
  86034. */
  86035. this.onDisposeObservable = new BABYLON.Observable();
  86036. /**
  86037. * An event triggered before rendering the scene
  86038. * @type {BABYLON.Observable}
  86039. */
  86040. this.onBeforeRenderObservable = new BABYLON.Observable();
  86041. /**
  86042. * An event triggered after rendering the scene
  86043. * @type {BABYLON.Observable}
  86044. */
  86045. this.onAfterRenderObservable = new BABYLON.Observable();
  86046. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86047. this.isBackground = isBackground === undefined ? true : isBackground;
  86048. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86049. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86050. this._scene.layers.push(this);
  86051. var engine = this._scene.getEngine();
  86052. // VBO
  86053. var vertices = [];
  86054. vertices.push(1, 1);
  86055. vertices.push(-1, 1);
  86056. vertices.push(-1, -1);
  86057. vertices.push(1, -1);
  86058. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86060. this._createIndexBuffer();
  86061. // Effects
  86062. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86063. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86064. }
  86065. Object.defineProperty(Layer.prototype, "onDispose", {
  86066. set: function (callback) {
  86067. if (this._onDisposeObserver) {
  86068. this.onDisposeObservable.remove(this._onDisposeObserver);
  86069. }
  86070. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86071. },
  86072. enumerable: true,
  86073. configurable: true
  86074. });
  86075. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86076. set: function (callback) {
  86077. if (this._onBeforeRenderObserver) {
  86078. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86079. }
  86080. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86081. },
  86082. enumerable: true,
  86083. configurable: true
  86084. });
  86085. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86086. set: function (callback) {
  86087. if (this._onAfterRenderObserver) {
  86088. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86089. }
  86090. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86091. },
  86092. enumerable: true,
  86093. configurable: true
  86094. });
  86095. Layer.prototype._createIndexBuffer = function () {
  86096. var engine = this._scene.getEngine();
  86097. // Indices
  86098. var indices = [];
  86099. indices.push(0);
  86100. indices.push(1);
  86101. indices.push(2);
  86102. indices.push(0);
  86103. indices.push(2);
  86104. indices.push(3);
  86105. this._indexBuffer = engine.createIndexBuffer(indices);
  86106. };
  86107. Layer.prototype._rebuild = function () {
  86108. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86109. if (vb) {
  86110. vb._rebuild();
  86111. }
  86112. this._createIndexBuffer();
  86113. };
  86114. Layer.prototype.render = function () {
  86115. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86116. // Check
  86117. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86118. return;
  86119. var engine = this._scene.getEngine();
  86120. this.onBeforeRenderObservable.notifyObservers(this);
  86121. // Render
  86122. engine.enableEffect(currentEffect);
  86123. engine.setState(false);
  86124. // Texture
  86125. currentEffect.setTexture("textureSampler", this.texture);
  86126. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86127. // Color
  86128. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86129. // Scale / offset
  86130. currentEffect.setVector2("offset", this.offset);
  86131. currentEffect.setVector2("scale", this.scale);
  86132. // VBOs
  86133. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86134. // Draw order
  86135. if (!this.alphaTest) {
  86136. engine.setAlphaMode(this.alphaBlendingMode);
  86137. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86138. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86139. }
  86140. else {
  86141. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86142. }
  86143. this.onAfterRenderObservable.notifyObservers(this);
  86144. };
  86145. Layer.prototype.dispose = function () {
  86146. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86147. if (vertexBuffer) {
  86148. vertexBuffer.dispose();
  86149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86150. }
  86151. if (this._indexBuffer) {
  86152. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86153. this._indexBuffer = null;
  86154. }
  86155. if (this.texture) {
  86156. this.texture.dispose();
  86157. this.texture = null;
  86158. }
  86159. // Remove from scene
  86160. var index = this._scene.layers.indexOf(this);
  86161. this._scene.layers.splice(index, 1);
  86162. // Callback
  86163. this.onDisposeObservable.notifyObservers(this);
  86164. this.onDisposeObservable.clear();
  86165. this.onAfterRenderObservable.clear();
  86166. this.onBeforeRenderObservable.clear();
  86167. };
  86168. return Layer;
  86169. }());
  86170. BABYLON.Layer = Layer;
  86171. })(BABYLON || (BABYLON = {}));
  86172. //# sourceMappingURL=babylon.layer.js.map
  86173. var BABYLON;
  86174. (function (BABYLON) {
  86175. var TextureTools = /** @class */ (function () {
  86176. function TextureTools() {
  86177. }
  86178. /**
  86179. * Uses the GPU to create a copy texture rescaled at a given size
  86180. * @param texture Texture to copy from
  86181. * @param width Desired width
  86182. * @param height Desired height
  86183. * @return Generated texture
  86184. */
  86185. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86186. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86187. var scene = texture.getScene();
  86188. var engine = scene.getEngine();
  86189. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86190. rtt.wrapU = texture.wrapU;
  86191. rtt.wrapV = texture.wrapV;
  86192. rtt.uOffset = texture.uOffset;
  86193. rtt.vOffset = texture.vOffset;
  86194. rtt.uScale = texture.uScale;
  86195. rtt.vScale = texture.vScale;
  86196. rtt.uAng = texture.uAng;
  86197. rtt.vAng = texture.vAng;
  86198. rtt.wAng = texture.wAng;
  86199. rtt.coordinatesIndex = texture.coordinatesIndex;
  86200. rtt.level = texture.level;
  86201. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86202. rtt._texture.isReady = false;
  86203. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86204. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86205. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86206. passPostProcess.getEffect().executeWhenCompiled(function () {
  86207. passPostProcess.onApply = function (effect) {
  86208. effect.setTexture("textureSampler", texture);
  86209. };
  86210. var internalTexture = rtt.getInternalTexture();
  86211. if (internalTexture) {
  86212. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86213. engine.unBindFramebuffer(internalTexture);
  86214. rtt.disposeFramebufferObjects();
  86215. passPostProcess.dispose();
  86216. internalTexture.isReady = true;
  86217. }
  86218. });
  86219. return rtt;
  86220. };
  86221. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86222. if (!scene._environmentBRDFTexture) {
  86223. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86224. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86225. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86226. scene._environmentBRDFTexture = texture;
  86227. }
  86228. return scene._environmentBRDFTexture;
  86229. };
  86230. 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=";
  86231. return TextureTools;
  86232. }());
  86233. BABYLON.TextureTools = TextureTools;
  86234. })(BABYLON || (BABYLON = {}));
  86235. //# sourceMappingURL=babylon.textureTools.js.map
  86236. var BABYLON;
  86237. (function (BABYLON) {
  86238. var FramingBehavior = /** @class */ (function () {
  86239. function FramingBehavior() {
  86240. this._mode = FramingBehavior.FitFrustumSidesMode;
  86241. this._radiusScale = 1.0;
  86242. this._positionScale = 0.5;
  86243. this._defaultElevation = 0.3;
  86244. this._elevationReturnTime = 1500;
  86245. this._elevationReturnWaitTime = 1000;
  86246. this._zoomStopsAnimation = false;
  86247. this._framingTime = 1500;
  86248. this._isPointerDown = false;
  86249. this._lastInteractionTime = -Infinity;
  86250. // Framing control
  86251. this._animatables = new Array();
  86252. this._betaIsAnimating = false;
  86253. }
  86254. Object.defineProperty(FramingBehavior.prototype, "name", {
  86255. get: function () {
  86256. return "Framing";
  86257. },
  86258. enumerable: true,
  86259. configurable: true
  86260. });
  86261. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86262. /**
  86263. * Gets current mode used by the behavior.
  86264. */
  86265. get: function () {
  86266. return this._mode;
  86267. },
  86268. /**
  86269. * Sets the current mode used by the behavior
  86270. */
  86271. set: function (mode) {
  86272. this._mode = mode;
  86273. },
  86274. enumerable: true,
  86275. configurable: true
  86276. });
  86277. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86278. /**
  86279. * Gets the scale applied to the radius
  86280. */
  86281. get: function () {
  86282. return this._radiusScale;
  86283. },
  86284. /**
  86285. * Sets the scale applied to the radius (1 by default)
  86286. */
  86287. set: function (radius) {
  86288. this._radiusScale = radius;
  86289. },
  86290. enumerable: true,
  86291. configurable: true
  86292. });
  86293. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86294. /**
  86295. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86296. */
  86297. get: function () {
  86298. return this._positionScale;
  86299. },
  86300. /**
  86301. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86302. */
  86303. set: function (scale) {
  86304. this._positionScale = scale;
  86305. },
  86306. enumerable: true,
  86307. configurable: true
  86308. });
  86309. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86310. /**
  86311. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86312. * behaviour is triggered, in radians.
  86313. */
  86314. get: function () {
  86315. return this._defaultElevation;
  86316. },
  86317. /**
  86318. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86319. * behaviour is triggered, in radians.
  86320. */
  86321. set: function (elevation) {
  86322. this._defaultElevation = elevation;
  86323. },
  86324. enumerable: true,
  86325. configurable: true
  86326. });
  86327. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86328. /**
  86329. * Gets the time (in milliseconds) taken to return to the default beta position.
  86330. * Negative value indicates camera should not return to default.
  86331. */
  86332. get: function () {
  86333. return this._elevationReturnTime;
  86334. },
  86335. /**
  86336. * Sets the time (in milliseconds) taken to return to the default beta position.
  86337. * Negative value indicates camera should not return to default.
  86338. */
  86339. set: function (speed) {
  86340. this._elevationReturnTime = speed;
  86341. },
  86342. enumerable: true,
  86343. configurable: true
  86344. });
  86345. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86346. /**
  86347. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86348. */
  86349. get: function () {
  86350. return this._elevationReturnWaitTime;
  86351. },
  86352. /**
  86353. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86354. */
  86355. set: function (time) {
  86356. this._elevationReturnWaitTime = time;
  86357. },
  86358. enumerable: true,
  86359. configurable: true
  86360. });
  86361. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86362. /**
  86363. * Gets the flag that indicates if user zooming should stop animation.
  86364. */
  86365. get: function () {
  86366. return this._zoomStopsAnimation;
  86367. },
  86368. /**
  86369. * Sets the flag that indicates if user zooming should stop animation.
  86370. */
  86371. set: function (flag) {
  86372. this._zoomStopsAnimation = flag;
  86373. },
  86374. enumerable: true,
  86375. configurable: true
  86376. });
  86377. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86378. /**
  86379. * Gets the transition time when framing the mesh, in milliseconds
  86380. */
  86381. get: function () {
  86382. return this._framingTime;
  86383. },
  86384. /**
  86385. * Sets the transition time when framing the mesh, in milliseconds
  86386. */
  86387. set: function (time) {
  86388. this._framingTime = time;
  86389. },
  86390. enumerable: true,
  86391. configurable: true
  86392. });
  86393. FramingBehavior.prototype.init = function () {
  86394. // Do notihng
  86395. };
  86396. FramingBehavior.prototype.attach = function (camera) {
  86397. var _this = this;
  86398. this._attachedCamera = camera;
  86399. var scene = this._attachedCamera.getScene();
  86400. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86401. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86402. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86403. _this._isPointerDown = true;
  86404. return;
  86405. }
  86406. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86407. _this._isPointerDown = false;
  86408. }
  86409. });
  86410. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86411. if (mesh) {
  86412. _this.zoomOnMesh(mesh);
  86413. }
  86414. });
  86415. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86416. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86417. _this._applyUserInteraction();
  86418. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86419. // back to the default position after a given timeout
  86420. _this._maintainCameraAboveGround();
  86421. });
  86422. };
  86423. FramingBehavior.prototype.detach = function () {
  86424. if (!this._attachedCamera) {
  86425. return;
  86426. }
  86427. var scene = this._attachedCamera.getScene();
  86428. if (this._onPrePointerObservableObserver) {
  86429. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86430. }
  86431. if (this._onAfterCheckInputsObserver) {
  86432. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86433. }
  86434. if (this._onMeshTargetChangedObserver) {
  86435. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86436. }
  86437. this._attachedCamera = null;
  86438. };
  86439. /**
  86440. * Targets the given mesh and updates zoom level accordingly.
  86441. * @param mesh The mesh to target.
  86442. * @param radius Optional. If a cached radius position already exists, overrides default.
  86443. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86444. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86445. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86446. */
  86447. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86448. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86449. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86450. mesh.computeWorldMatrix(true);
  86451. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86452. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86453. };
  86454. /**
  86455. * Targets the given mesh with its children and updates zoom level accordingly.
  86456. * @param mesh The mesh to target.
  86457. * @param radius Optional. If a cached radius position already exists, overrides default.
  86458. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86459. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86460. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86461. */
  86462. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86463. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86464. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86465. mesh.computeWorldMatrix(true);
  86466. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86467. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86468. };
  86469. /**
  86470. * Targets the given meshes with their children and updates zoom level accordingly.
  86471. * @param meshes The mesh to target.
  86472. * @param radius Optional. If a cached radius position already exists, overrides default.
  86473. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86474. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86475. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86476. */
  86477. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86478. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86479. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86480. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86481. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86482. for (var i = 0; i < meshes.length; i++) {
  86483. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86484. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86485. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86486. }
  86487. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86488. };
  86489. /**
  86490. * Targets the given mesh and updates zoom level accordingly.
  86491. * @param mesh The mesh to target.
  86492. * @param radius Optional. If a cached radius position already exists, overrides default.
  86493. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86494. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86495. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86496. */
  86497. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86498. var _this = this;
  86499. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86500. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86501. var zoomTarget;
  86502. if (!this._attachedCamera) {
  86503. return;
  86504. }
  86505. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86506. var bottom = minimumWorld.y;
  86507. var top = maximumWorld.y;
  86508. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86509. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86510. if (focusOnOriginXZ) {
  86511. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86512. }
  86513. else {
  86514. var centerWorld = minimumWorld.add(radiusWorld);
  86515. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86516. }
  86517. if (!this._vectorTransition) {
  86518. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86519. }
  86520. this._betaIsAnimating = true;
  86521. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86522. if (animatable) {
  86523. this._animatables.push(animatable);
  86524. }
  86525. // sets the radius and lower radius bounds
  86526. // Small delta ensures camera is not always at lower zoom limit.
  86527. var radius = 0;
  86528. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86529. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86530. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86531. radius = position;
  86532. }
  86533. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86534. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86535. if (this._attachedCamera.lowerRadiusLimit === null) {
  86536. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86537. }
  86538. }
  86539. // Set sensibilities
  86540. var extend = maximumWorld.subtract(minimumWorld).length();
  86541. this._attachedCamera.panningSensibility = 5000 / extend;
  86542. this._attachedCamera.wheelPrecision = 100 / radius;
  86543. // transition to new radius
  86544. if (!this._radiusTransition) {
  86545. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86546. }
  86547. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86548. if (onAnimationEnd) {
  86549. onAnimationEnd();
  86550. }
  86551. if (_this._attachedCamera) {
  86552. _this._attachedCamera.storeState();
  86553. }
  86554. });
  86555. if (animatable) {
  86556. this._animatables.push(animatable);
  86557. }
  86558. };
  86559. /**
  86560. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86561. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86562. * frustum width.
  86563. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86564. * to fully enclose the mesh in the viewing frustum.
  86565. */
  86566. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86567. var size = maximumWorld.subtract(minimumWorld);
  86568. var boxVectorGlobalDiagonal = size.length();
  86569. var frustumSlope = this._getFrustumSlope();
  86570. // Formula for setting distance
  86571. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86572. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86573. // Horizon distance
  86574. var radius = radiusWithoutFraming * this._radiusScale;
  86575. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86576. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86577. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86578. var camera = this._attachedCamera;
  86579. if (!camera) {
  86580. return 0;
  86581. }
  86582. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86583. // Don't exceed the requested limit
  86584. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86585. }
  86586. // Don't exceed the upper radius limit
  86587. if (camera.upperRadiusLimit) {
  86588. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86589. }
  86590. return distance;
  86591. };
  86592. /**
  86593. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86594. * is automatically returned to its default position (expected to be above ground plane).
  86595. */
  86596. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86597. var _this = this;
  86598. if (this._elevationReturnTime < 0) {
  86599. return;
  86600. }
  86601. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86602. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86603. var limitBeta = Math.PI * 0.5;
  86604. // Bring the camera back up if below the ground plane
  86605. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86606. this._betaIsAnimating = true;
  86607. //Transition to new position
  86608. this.stopAllAnimations();
  86609. if (!this._betaTransition) {
  86610. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86611. }
  86612. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86613. _this._clearAnimationLocks();
  86614. _this.stopAllAnimations();
  86615. });
  86616. if (animatabe) {
  86617. this._animatables.push(animatabe);
  86618. }
  86619. }
  86620. };
  86621. /**
  86622. * Returns the frustum slope based on the canvas ratio and camera FOV
  86623. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86624. */
  86625. FramingBehavior.prototype._getFrustumSlope = function () {
  86626. // Calculate the viewport ratio
  86627. // Aspect Ratio is Height/Width.
  86628. var camera = this._attachedCamera;
  86629. if (!camera) {
  86630. return BABYLON.Vector2.Zero();
  86631. }
  86632. var engine = camera.getScene().getEngine();
  86633. var aspectRatio = engine.getAspectRatio(camera);
  86634. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86635. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86636. var frustumSlopeY = Math.tan(camera.fov / 2);
  86637. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86638. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86639. // along the forward vector.
  86640. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86641. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86642. };
  86643. /**
  86644. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86645. */
  86646. FramingBehavior.prototype._clearAnimationLocks = function () {
  86647. this._betaIsAnimating = false;
  86648. };
  86649. /**
  86650. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86651. */
  86652. FramingBehavior.prototype._applyUserInteraction = function () {
  86653. if (this.isUserIsMoving) {
  86654. this._lastInteractionTime = BABYLON.Tools.Now;
  86655. this.stopAllAnimations();
  86656. this._clearAnimationLocks();
  86657. }
  86658. };
  86659. /**
  86660. * Stops and removes all animations that have been applied to the camera
  86661. */
  86662. FramingBehavior.prototype.stopAllAnimations = function () {
  86663. if (this._attachedCamera) {
  86664. this._attachedCamera.animations = [];
  86665. }
  86666. while (this._animatables.length) {
  86667. if (this._animatables[0]) {
  86668. this._animatables[0].onAnimationEnd = null;
  86669. this._animatables[0].stop();
  86670. }
  86671. this._animatables.shift();
  86672. }
  86673. };
  86674. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86675. /**
  86676. * Gets a value indicating if the user is moving the camera
  86677. */
  86678. get: function () {
  86679. if (!this._attachedCamera) {
  86680. return false;
  86681. }
  86682. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86683. this._attachedCamera.inertialBetaOffset !== 0 ||
  86684. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86685. this._attachedCamera.inertialPanningX !== 0 ||
  86686. this._attachedCamera.inertialPanningY !== 0 ||
  86687. this._isPointerDown;
  86688. },
  86689. enumerable: true,
  86690. configurable: true
  86691. });
  86692. /**
  86693. * The easing function used by animations
  86694. */
  86695. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86696. /**
  86697. * The easing mode used by animations
  86698. */
  86699. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86700. // Statics
  86701. /**
  86702. * The camera can move all the way towards the mesh.
  86703. */
  86704. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86705. /**
  86706. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86707. */
  86708. FramingBehavior.FitFrustumSidesMode = 1;
  86709. return FramingBehavior;
  86710. }());
  86711. BABYLON.FramingBehavior = FramingBehavior;
  86712. })(BABYLON || (BABYLON = {}));
  86713. //# sourceMappingURL=babylon.framingBehavior.js.map
  86714. var BABYLON;
  86715. (function (BABYLON) {
  86716. /**
  86717. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86718. */
  86719. var BouncingBehavior = /** @class */ (function () {
  86720. function BouncingBehavior() {
  86721. /**
  86722. * The duration of the animation, in milliseconds
  86723. */
  86724. this.transitionDuration = 450;
  86725. /**
  86726. * Length of the distance animated by the transition when lower radius is reached
  86727. */
  86728. this.lowerRadiusTransitionRange = 2;
  86729. /**
  86730. * Length of the distance animated by the transition when upper radius is reached
  86731. */
  86732. this.upperRadiusTransitionRange = -2;
  86733. this._autoTransitionRange = false;
  86734. // Animations
  86735. this._radiusIsAnimating = false;
  86736. this._radiusBounceTransition = null;
  86737. this._animatables = new Array();
  86738. }
  86739. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86740. get: function () {
  86741. return "Bouncing";
  86742. },
  86743. enumerable: true,
  86744. configurable: true
  86745. });
  86746. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86747. /**
  86748. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86749. */
  86750. get: function () {
  86751. return this._autoTransitionRange;
  86752. },
  86753. /**
  86754. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86755. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86756. */
  86757. set: function (value) {
  86758. var _this = this;
  86759. if (this._autoTransitionRange === value) {
  86760. return;
  86761. }
  86762. this._autoTransitionRange = value;
  86763. var camera = this._attachedCamera;
  86764. if (!camera) {
  86765. return;
  86766. }
  86767. if (value) {
  86768. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86769. if (!mesh) {
  86770. return;
  86771. }
  86772. mesh.computeWorldMatrix(true);
  86773. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86774. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86775. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86776. });
  86777. }
  86778. else if (this._onMeshTargetChangedObserver) {
  86779. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86780. }
  86781. },
  86782. enumerable: true,
  86783. configurable: true
  86784. });
  86785. BouncingBehavior.prototype.init = function () {
  86786. // Do notihng
  86787. };
  86788. BouncingBehavior.prototype.attach = function (camera) {
  86789. var _this = this;
  86790. this._attachedCamera = camera;
  86791. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86792. if (!_this._attachedCamera) {
  86793. return;
  86794. }
  86795. // Add the bounce animation to the lower radius limit
  86796. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86797. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86798. }
  86799. // Add the bounce animation to the upper radius limit
  86800. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86801. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86802. }
  86803. });
  86804. };
  86805. BouncingBehavior.prototype.detach = function () {
  86806. if (!this._attachedCamera) {
  86807. return;
  86808. }
  86809. if (this._onAfterCheckInputsObserver) {
  86810. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86811. }
  86812. if (this._onMeshTargetChangedObserver) {
  86813. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86814. }
  86815. this._attachedCamera = null;
  86816. };
  86817. /**
  86818. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86819. * @param radiusLimit The limit to check against.
  86820. * @return Bool to indicate if at limit.
  86821. */
  86822. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86823. if (!this._attachedCamera) {
  86824. return false;
  86825. }
  86826. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86827. return true;
  86828. }
  86829. return false;
  86830. };
  86831. /**
  86832. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86833. * @param radiusDelta The delta by which to animate to. Can be negative.
  86834. */
  86835. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86836. var _this = this;
  86837. if (!this._attachedCamera) {
  86838. return;
  86839. }
  86840. if (!this._radiusBounceTransition) {
  86841. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86842. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86843. }
  86844. // Prevent zoom until bounce has completed
  86845. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86846. this._attachedCamera.wheelPrecision = Infinity;
  86847. this._attachedCamera.inertialRadiusOffset = 0;
  86848. // Animate to the radius limit
  86849. this.stopAllAnimations();
  86850. this._radiusIsAnimating = true;
  86851. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86852. if (animatable) {
  86853. this._animatables.push(animatable);
  86854. }
  86855. };
  86856. /**
  86857. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86858. */
  86859. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86860. this._radiusIsAnimating = false;
  86861. if (this._attachedCamera) {
  86862. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86863. }
  86864. };
  86865. /**
  86866. * Stops and removes all animations that have been applied to the camera
  86867. */
  86868. BouncingBehavior.prototype.stopAllAnimations = function () {
  86869. if (this._attachedCamera) {
  86870. this._attachedCamera.animations = [];
  86871. }
  86872. while (this._animatables.length) {
  86873. this._animatables[0].onAnimationEnd = null;
  86874. this._animatables[0].stop();
  86875. this._animatables.shift();
  86876. }
  86877. };
  86878. /**
  86879. * The easing function used by animations
  86880. */
  86881. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86882. /**
  86883. * The easing mode used by animations
  86884. */
  86885. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86886. return BouncingBehavior;
  86887. }());
  86888. BABYLON.BouncingBehavior = BouncingBehavior;
  86889. })(BABYLON || (BABYLON = {}));
  86890. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86891. var BABYLON;
  86892. (function (BABYLON) {
  86893. var AutoRotationBehavior = /** @class */ (function () {
  86894. function AutoRotationBehavior() {
  86895. this._zoomStopsAnimation = false;
  86896. this._idleRotationSpeed = 0.05;
  86897. this._idleRotationWaitTime = 2000;
  86898. this._idleRotationSpinupTime = 2000;
  86899. this._isPointerDown = false;
  86900. this._lastFrameTime = null;
  86901. this._lastInteractionTime = -Infinity;
  86902. this._cameraRotationSpeed = 0;
  86903. this._lastFrameRadius = 0;
  86904. }
  86905. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86906. get: function () {
  86907. return "AutoRotation";
  86908. },
  86909. enumerable: true,
  86910. configurable: true
  86911. });
  86912. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86913. /**
  86914. * Gets the flag that indicates if user zooming should stop animation.
  86915. */
  86916. get: function () {
  86917. return this._zoomStopsAnimation;
  86918. },
  86919. /**
  86920. * Sets the flag that indicates if user zooming should stop animation.
  86921. */
  86922. set: function (flag) {
  86923. this._zoomStopsAnimation = flag;
  86924. },
  86925. enumerable: true,
  86926. configurable: true
  86927. });
  86928. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86929. /**
  86930. * Gets the default speed at which the camera rotates around the model.
  86931. */
  86932. get: function () {
  86933. return this._idleRotationSpeed;
  86934. },
  86935. /**
  86936. * Sets the default speed at which the camera rotates around the model.
  86937. */
  86938. set: function (speed) {
  86939. this._idleRotationSpeed = speed;
  86940. },
  86941. enumerable: true,
  86942. configurable: true
  86943. });
  86944. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  86945. /**
  86946. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  86947. */
  86948. get: function () {
  86949. return this._idleRotationWaitTime;
  86950. },
  86951. /**
  86952. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  86953. */
  86954. set: function (time) {
  86955. this._idleRotationWaitTime = time;
  86956. },
  86957. enumerable: true,
  86958. configurable: true
  86959. });
  86960. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  86961. /**
  86962. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86963. */
  86964. get: function () {
  86965. return this._idleRotationSpinupTime;
  86966. },
  86967. /**
  86968. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86969. */
  86970. set: function (time) {
  86971. this._idleRotationSpinupTime = time;
  86972. },
  86973. enumerable: true,
  86974. configurable: true
  86975. });
  86976. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  86977. /**
  86978. * Gets a value indicating if the camera is currently rotating because of this behavior
  86979. */
  86980. get: function () {
  86981. return Math.abs(this._cameraRotationSpeed) > 0;
  86982. },
  86983. enumerable: true,
  86984. configurable: true
  86985. });
  86986. AutoRotationBehavior.prototype.init = function () {
  86987. // Do notihng
  86988. };
  86989. AutoRotationBehavior.prototype.attach = function (camera) {
  86990. var _this = this;
  86991. this._attachedCamera = camera;
  86992. var scene = this._attachedCamera.getScene();
  86993. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86994. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86995. _this._isPointerDown = true;
  86996. return;
  86997. }
  86998. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86999. _this._isPointerDown = false;
  87000. }
  87001. });
  87002. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87003. var now = BABYLON.Tools.Now;
  87004. var dt = 0;
  87005. if (_this._lastFrameTime != null) {
  87006. dt = now - _this._lastFrameTime;
  87007. }
  87008. _this._lastFrameTime = now;
  87009. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87010. _this._applyUserInteraction();
  87011. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87012. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87013. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87014. // Step camera rotation by rotation speed
  87015. if (_this._attachedCamera) {
  87016. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87017. }
  87018. });
  87019. };
  87020. AutoRotationBehavior.prototype.detach = function () {
  87021. if (!this._attachedCamera) {
  87022. return;
  87023. }
  87024. var scene = this._attachedCamera.getScene();
  87025. if (this._onPrePointerObservableObserver) {
  87026. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87027. }
  87028. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87029. this._attachedCamera = null;
  87030. };
  87031. /**
  87032. * Returns true if user is scrolling.
  87033. * @return true if user is scrolling.
  87034. */
  87035. AutoRotationBehavior.prototype._userIsZooming = function () {
  87036. if (!this._attachedCamera) {
  87037. return false;
  87038. }
  87039. return this._attachedCamera.inertialRadiusOffset !== 0;
  87040. };
  87041. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87042. if (!this._attachedCamera) {
  87043. return false;
  87044. }
  87045. var zoomHasHitLimit = false;
  87046. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87047. zoomHasHitLimit = true;
  87048. }
  87049. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87050. this._lastFrameRadius = this._attachedCamera.radius;
  87051. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87052. };
  87053. /**
  87054. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87055. */
  87056. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87057. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87058. this._lastInteractionTime = BABYLON.Tools.Now;
  87059. }
  87060. };
  87061. // Tools
  87062. AutoRotationBehavior.prototype._userIsMoving = function () {
  87063. if (!this._attachedCamera) {
  87064. return false;
  87065. }
  87066. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87067. this._attachedCamera.inertialBetaOffset !== 0 ||
  87068. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87069. this._attachedCamera.inertialPanningX !== 0 ||
  87070. this._attachedCamera.inertialPanningY !== 0 ||
  87071. this._isPointerDown;
  87072. };
  87073. return AutoRotationBehavior;
  87074. }());
  87075. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87076. })(BABYLON || (BABYLON = {}));
  87077. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87078. var BABYLON;
  87079. (function (BABYLON) {
  87080. /**
  87081. * This class can be used to get instrumentation data from a Babylon engine
  87082. */
  87083. var EngineInstrumentation = /** @class */ (function () {
  87084. function EngineInstrumentation(engine) {
  87085. this.engine = engine;
  87086. this._captureGPUFrameTime = false;
  87087. this._gpuFrameTime = new BABYLON.PerfCounter();
  87088. this._captureShaderCompilationTime = false;
  87089. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87090. // Observers
  87091. this._onBeginFrameObserver = null;
  87092. this._onEndFrameObserver = null;
  87093. this._onBeforeShaderCompilationObserver = null;
  87094. this._onAfterShaderCompilationObserver = null;
  87095. }
  87096. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87097. // Properties
  87098. /**
  87099. * Gets the perf counter used for GPU frame time
  87100. */
  87101. get: function () {
  87102. return this._gpuFrameTime;
  87103. },
  87104. enumerable: true,
  87105. configurable: true
  87106. });
  87107. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87108. /**
  87109. * Gets the GPU frame time capture status
  87110. */
  87111. get: function () {
  87112. return this._captureGPUFrameTime;
  87113. },
  87114. /**
  87115. * Enable or disable the GPU frame time capture
  87116. */
  87117. set: function (value) {
  87118. var _this = this;
  87119. if (value === this._captureGPUFrameTime) {
  87120. return;
  87121. }
  87122. this._captureGPUFrameTime = value;
  87123. if (value) {
  87124. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87125. if (!_this._gpuFrameTimeToken) {
  87126. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87127. }
  87128. });
  87129. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87130. if (!_this._gpuFrameTimeToken) {
  87131. return;
  87132. }
  87133. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87134. if (time > -1) {
  87135. _this._gpuFrameTimeToken = null;
  87136. _this._gpuFrameTime.fetchNewFrame();
  87137. _this._gpuFrameTime.addCount(time, true);
  87138. }
  87139. });
  87140. }
  87141. else {
  87142. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87143. this._onBeginFrameObserver = null;
  87144. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87145. this._onEndFrameObserver = null;
  87146. }
  87147. },
  87148. enumerable: true,
  87149. configurable: true
  87150. });
  87151. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87152. /**
  87153. * Gets the perf counter used for shader compilation time
  87154. */
  87155. get: function () {
  87156. return this._shaderCompilationTime;
  87157. },
  87158. enumerable: true,
  87159. configurable: true
  87160. });
  87161. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87162. /**
  87163. * Gets the shader compilation time capture status
  87164. */
  87165. get: function () {
  87166. return this._captureShaderCompilationTime;
  87167. },
  87168. /**
  87169. * Enable or disable the shader compilation time capture
  87170. */
  87171. set: function (value) {
  87172. var _this = this;
  87173. if (value === this._captureShaderCompilationTime) {
  87174. return;
  87175. }
  87176. this._captureShaderCompilationTime = value;
  87177. if (value) {
  87178. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87179. _this._shaderCompilationTime.fetchNewFrame();
  87180. _this._shaderCompilationTime.beginMonitoring();
  87181. });
  87182. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87183. _this._shaderCompilationTime.endMonitoring();
  87184. });
  87185. }
  87186. else {
  87187. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87188. this._onBeforeShaderCompilationObserver = null;
  87189. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87190. this._onAfterShaderCompilationObserver = null;
  87191. }
  87192. },
  87193. enumerable: true,
  87194. configurable: true
  87195. });
  87196. EngineInstrumentation.prototype.dispose = function () {
  87197. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87198. this._onBeginFrameObserver = null;
  87199. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87200. this._onEndFrameObserver = null;
  87201. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87202. this._onBeforeShaderCompilationObserver = null;
  87203. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87204. this._onAfterShaderCompilationObserver = null;
  87205. this.engine = null;
  87206. };
  87207. return EngineInstrumentation;
  87208. }());
  87209. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87210. })(BABYLON || (BABYLON = {}));
  87211. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87212. var BABYLON;
  87213. (function (BABYLON) {
  87214. /**
  87215. * This class can be used to get instrumentation data from a Babylon engine
  87216. */
  87217. var SceneInstrumentation = /** @class */ (function () {
  87218. function SceneInstrumentation(scene) {
  87219. var _this = this;
  87220. this.scene = scene;
  87221. this._captureActiveMeshesEvaluationTime = false;
  87222. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87223. this._captureRenderTargetsRenderTime = false;
  87224. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87225. this._captureFrameTime = false;
  87226. this._frameTime = new BABYLON.PerfCounter();
  87227. this._captureRenderTime = false;
  87228. this._renderTime = new BABYLON.PerfCounter();
  87229. this._captureInterFrameTime = false;
  87230. this._interFrameTime = new BABYLON.PerfCounter();
  87231. this._captureParticlesRenderTime = false;
  87232. this._particlesRenderTime = new BABYLON.PerfCounter();
  87233. this._captureSpritesRenderTime = false;
  87234. this._spritesRenderTime = new BABYLON.PerfCounter();
  87235. this._capturePhysicsTime = false;
  87236. this._physicsTime = new BABYLON.PerfCounter();
  87237. this._captureAnimationsTime = false;
  87238. this._animationsTime = new BABYLON.PerfCounter();
  87239. // Observers
  87240. this._onBeforeActiveMeshesEvaluationObserver = null;
  87241. this._onAfterActiveMeshesEvaluationObserver = null;
  87242. this._onBeforeRenderTargetsRenderObserver = null;
  87243. this._onAfterRenderTargetsRenderObserver = null;
  87244. this._onAfterRenderObserver = null;
  87245. this._onBeforeDrawPhaseObserver = null;
  87246. this._onAfterDrawPhaseObserver = null;
  87247. this._onBeforeAnimationsObserver = null;
  87248. this._onBeforeParticlesRenderingObserver = null;
  87249. this._onAfterParticlesRenderingObserver = null;
  87250. this._onBeforeSpritesRenderingObserver = null;
  87251. this._onAfterSpritesRenderingObserver = null;
  87252. this._onBeforePhysicsObserver = null;
  87253. this._onAfterPhysicsObserver = null;
  87254. this._onAfterAnimationsObserver = null;
  87255. // Before render
  87256. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87257. if (_this._captureActiveMeshesEvaluationTime) {
  87258. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87259. }
  87260. if (_this._captureRenderTargetsRenderTime) {
  87261. _this._renderTargetsRenderTime.fetchNewFrame();
  87262. }
  87263. if (_this._captureFrameTime) {
  87264. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87265. _this._frameTime.beginMonitoring();
  87266. }
  87267. if (_this._captureInterFrameTime) {
  87268. _this._interFrameTime.endMonitoring();
  87269. }
  87270. if (_this._captureParticlesRenderTime) {
  87271. _this._particlesRenderTime.fetchNewFrame();
  87272. }
  87273. if (_this._captureSpritesRenderTime) {
  87274. _this._spritesRenderTime.fetchNewFrame();
  87275. }
  87276. if (_this._captureAnimationsTime) {
  87277. _this._animationsTime.beginMonitoring();
  87278. }
  87279. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87280. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87281. });
  87282. // After render
  87283. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87284. if (_this._captureFrameTime) {
  87285. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87286. _this._frameTime.endMonitoring();
  87287. }
  87288. if (_this._captureRenderTime) {
  87289. _this._renderTime.endMonitoring(false);
  87290. }
  87291. if (_this._captureInterFrameTime) {
  87292. _this._interFrameTime.beginMonitoring();
  87293. }
  87294. });
  87295. }
  87296. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87297. // Properties
  87298. /**
  87299. * Gets the perf counter used for active meshes evaluation time
  87300. */
  87301. get: function () {
  87302. return this._activeMeshesEvaluationTime;
  87303. },
  87304. enumerable: true,
  87305. configurable: true
  87306. });
  87307. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87308. /**
  87309. * Gets the active meshes evaluation time capture status
  87310. */
  87311. get: function () {
  87312. return this._captureActiveMeshesEvaluationTime;
  87313. },
  87314. /**
  87315. * Enable or disable the active meshes evaluation time capture
  87316. */
  87317. set: function (value) {
  87318. var _this = this;
  87319. if (value === this._captureActiveMeshesEvaluationTime) {
  87320. return;
  87321. }
  87322. this._captureActiveMeshesEvaluationTime = value;
  87323. if (value) {
  87324. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87325. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87326. _this._activeMeshesEvaluationTime.beginMonitoring();
  87327. });
  87328. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87329. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87330. _this._activeMeshesEvaluationTime.endMonitoring();
  87331. });
  87332. }
  87333. else {
  87334. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87335. this._onBeforeActiveMeshesEvaluationObserver = null;
  87336. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87337. this._onAfterActiveMeshesEvaluationObserver = null;
  87338. }
  87339. },
  87340. enumerable: true,
  87341. configurable: true
  87342. });
  87343. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87344. /**
  87345. * Gets the perf counter used for render targets render time
  87346. */
  87347. get: function () {
  87348. return this._renderTargetsRenderTime;
  87349. },
  87350. enumerable: true,
  87351. configurable: true
  87352. });
  87353. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87354. /**
  87355. * Gets the render targets render time capture status
  87356. */
  87357. get: function () {
  87358. return this._captureRenderTargetsRenderTime;
  87359. },
  87360. /**
  87361. * Enable or disable the render targets render time capture
  87362. */
  87363. set: function (value) {
  87364. var _this = this;
  87365. if (value === this._captureRenderTargetsRenderTime) {
  87366. return;
  87367. }
  87368. this._captureRenderTargetsRenderTime = value;
  87369. if (value) {
  87370. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87371. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87372. _this._renderTargetsRenderTime.beginMonitoring();
  87373. });
  87374. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87375. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87376. _this._renderTargetsRenderTime.endMonitoring(false);
  87377. });
  87378. }
  87379. else {
  87380. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87381. this._onBeforeRenderTargetsRenderObserver = null;
  87382. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87383. this._onAfterRenderTargetsRenderObserver = null;
  87384. }
  87385. },
  87386. enumerable: true,
  87387. configurable: true
  87388. });
  87389. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87390. /**
  87391. * Gets the perf counter used for particles render time
  87392. */
  87393. get: function () {
  87394. return this._particlesRenderTime;
  87395. },
  87396. enumerable: true,
  87397. configurable: true
  87398. });
  87399. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87400. /**
  87401. * Gets the particles render time capture status
  87402. */
  87403. get: function () {
  87404. return this._captureParticlesRenderTime;
  87405. },
  87406. /**
  87407. * Enable or disable the particles render time capture
  87408. */
  87409. set: function (value) {
  87410. var _this = this;
  87411. if (value === this._captureParticlesRenderTime) {
  87412. return;
  87413. }
  87414. this._captureParticlesRenderTime = value;
  87415. if (value) {
  87416. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87417. BABYLON.Tools.StartPerformanceCounter("Particles");
  87418. _this._particlesRenderTime.beginMonitoring();
  87419. });
  87420. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87421. BABYLON.Tools.EndPerformanceCounter("Particles");
  87422. _this._particlesRenderTime.endMonitoring(false);
  87423. });
  87424. }
  87425. else {
  87426. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87427. this._onBeforeParticlesRenderingObserver = null;
  87428. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87429. this._onAfterParticlesRenderingObserver = null;
  87430. }
  87431. },
  87432. enumerable: true,
  87433. configurable: true
  87434. });
  87435. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87436. /**
  87437. * Gets the perf counter used for sprites render time
  87438. */
  87439. get: function () {
  87440. return this._spritesRenderTime;
  87441. },
  87442. enumerable: true,
  87443. configurable: true
  87444. });
  87445. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87446. /**
  87447. * Gets the sprites render time capture status
  87448. */
  87449. get: function () {
  87450. return this._captureSpritesRenderTime;
  87451. },
  87452. /**
  87453. * Enable or disable the sprites render time capture
  87454. */
  87455. set: function (value) {
  87456. var _this = this;
  87457. if (value === this._captureSpritesRenderTime) {
  87458. return;
  87459. }
  87460. this._captureSpritesRenderTime = value;
  87461. if (value) {
  87462. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87463. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87464. _this._spritesRenderTime.beginMonitoring();
  87465. });
  87466. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87467. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87468. _this._spritesRenderTime.endMonitoring(false);
  87469. });
  87470. }
  87471. else {
  87472. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87473. this._onBeforeSpritesRenderingObserver = null;
  87474. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87475. this._onAfterSpritesRenderingObserver = null;
  87476. }
  87477. },
  87478. enumerable: true,
  87479. configurable: true
  87480. });
  87481. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87482. /**
  87483. * Gets the perf counter used for physics time
  87484. */
  87485. get: function () {
  87486. return this._physicsTime;
  87487. },
  87488. enumerable: true,
  87489. configurable: true
  87490. });
  87491. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87492. /**
  87493. * Gets the physics time capture status
  87494. */
  87495. get: function () {
  87496. return this._capturePhysicsTime;
  87497. },
  87498. /**
  87499. * Enable or disable the physics time capture
  87500. */
  87501. set: function (value) {
  87502. var _this = this;
  87503. if (value === this._capturePhysicsTime) {
  87504. return;
  87505. }
  87506. this._capturePhysicsTime = value;
  87507. if (value) {
  87508. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87509. BABYLON.Tools.StartPerformanceCounter("Physics");
  87510. _this._physicsTime.beginMonitoring();
  87511. });
  87512. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87513. BABYLON.Tools.EndPerformanceCounter("Physics");
  87514. _this._physicsTime.endMonitoring();
  87515. });
  87516. }
  87517. else {
  87518. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87519. this._onBeforePhysicsObserver = null;
  87520. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87521. this._onAfterPhysicsObserver = null;
  87522. }
  87523. },
  87524. enumerable: true,
  87525. configurable: true
  87526. });
  87527. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87528. /**
  87529. * Gets the perf counter used for animations time
  87530. */
  87531. get: function () {
  87532. return this._animationsTime;
  87533. },
  87534. enumerable: true,
  87535. configurable: true
  87536. });
  87537. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87538. /**
  87539. * Gets the animations time capture status
  87540. */
  87541. get: function () {
  87542. return this._captureAnimationsTime;
  87543. },
  87544. /**
  87545. * Enable or disable the animations time capture
  87546. */
  87547. set: function (value) {
  87548. var _this = this;
  87549. if (value === this._captureAnimationsTime) {
  87550. return;
  87551. }
  87552. this._captureAnimationsTime = value;
  87553. if (value) {
  87554. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87555. _this._animationsTime.endMonitoring();
  87556. });
  87557. }
  87558. else {
  87559. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87560. this._onAfterAnimationsObserver = null;
  87561. }
  87562. },
  87563. enumerable: true,
  87564. configurable: true
  87565. });
  87566. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87567. /**
  87568. * Gets the perf counter used for frame time capture
  87569. */
  87570. get: function () {
  87571. return this._frameTime;
  87572. },
  87573. enumerable: true,
  87574. configurable: true
  87575. });
  87576. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87577. /**
  87578. * Gets the frame time capture status
  87579. */
  87580. get: function () {
  87581. return this._captureFrameTime;
  87582. },
  87583. /**
  87584. * Enable or disable the frame time capture
  87585. */
  87586. set: function (value) {
  87587. this._captureFrameTime = value;
  87588. },
  87589. enumerable: true,
  87590. configurable: true
  87591. });
  87592. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87593. /**
  87594. * Gets the perf counter used for inter-frames time capture
  87595. */
  87596. get: function () {
  87597. return this._interFrameTime;
  87598. },
  87599. enumerable: true,
  87600. configurable: true
  87601. });
  87602. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87603. /**
  87604. * Gets the inter-frames time capture status
  87605. */
  87606. get: function () {
  87607. return this._captureInterFrameTime;
  87608. },
  87609. /**
  87610. * Enable or disable the inter-frames time capture
  87611. */
  87612. set: function (value) {
  87613. this._captureInterFrameTime = value;
  87614. },
  87615. enumerable: true,
  87616. configurable: true
  87617. });
  87618. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87619. /**
  87620. * Gets the perf counter used for render time capture
  87621. */
  87622. get: function () {
  87623. return this._renderTime;
  87624. },
  87625. enumerable: true,
  87626. configurable: true
  87627. });
  87628. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87629. /**
  87630. * Gets the render time capture status
  87631. */
  87632. get: function () {
  87633. return this._captureRenderTime;
  87634. },
  87635. /**
  87636. * Enable or disable the render time capture
  87637. */
  87638. set: function (value) {
  87639. var _this = this;
  87640. if (value === this._captureRenderTime) {
  87641. return;
  87642. }
  87643. this._captureRenderTime = value;
  87644. if (value) {
  87645. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87646. _this._renderTime.beginMonitoring();
  87647. BABYLON.Tools.StartPerformanceCounter("Main render");
  87648. });
  87649. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87650. _this._renderTime.endMonitoring(false);
  87651. BABYLON.Tools.EndPerformanceCounter("Main render");
  87652. });
  87653. }
  87654. else {
  87655. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87656. this._onBeforeDrawPhaseObserver = null;
  87657. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87658. this._onAfterDrawPhaseObserver = null;
  87659. }
  87660. },
  87661. enumerable: true,
  87662. configurable: true
  87663. });
  87664. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87665. /**
  87666. * Gets the perf counter used for draw calls
  87667. */
  87668. get: function () {
  87669. return this.scene.getEngine()._drawCalls;
  87670. },
  87671. enumerable: true,
  87672. configurable: true
  87673. });
  87674. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87675. /**
  87676. * Gets the perf counter used for texture collisions
  87677. */
  87678. get: function () {
  87679. return this.scene.getEngine()._textureCollisions;
  87680. },
  87681. enumerable: true,
  87682. configurable: true
  87683. });
  87684. SceneInstrumentation.prototype.dispose = function () {
  87685. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87686. this._onAfterRenderObserver = null;
  87687. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87688. this._onBeforeActiveMeshesEvaluationObserver = null;
  87689. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87690. this._onAfterActiveMeshesEvaluationObserver = null;
  87691. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87692. this._onBeforeRenderTargetsRenderObserver = null;
  87693. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87694. this._onAfterRenderTargetsRenderObserver = null;
  87695. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87696. this._onBeforeAnimationsObserver = null;
  87697. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87698. this._onBeforeParticlesRenderingObserver = null;
  87699. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87700. this._onAfterParticlesRenderingObserver = null;
  87701. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87702. this._onBeforeSpritesRenderingObserver = null;
  87703. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87704. this._onAfterSpritesRenderingObserver = null;
  87705. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87706. this._onBeforeDrawPhaseObserver = null;
  87707. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87708. this._onAfterDrawPhaseObserver = null;
  87709. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87710. this._onBeforePhysicsObserver = null;
  87711. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87712. this._onAfterPhysicsObserver = null;
  87713. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87714. this._onAfterAnimationsObserver = null;
  87715. this.scene = null;
  87716. };
  87717. return SceneInstrumentation;
  87718. }());
  87719. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87720. })(BABYLON || (BABYLON = {}));
  87721. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87722. var BABYLON;
  87723. (function (BABYLON) {
  87724. var _TimeToken = /** @class */ (function () {
  87725. function _TimeToken() {
  87726. this._timeElapsedQueryEnded = false;
  87727. }
  87728. return _TimeToken;
  87729. }());
  87730. BABYLON._TimeToken = _TimeToken;
  87731. })(BABYLON || (BABYLON = {}));
  87732. //# sourceMappingURL=babylon.timeToken.js.map
  87733. var BABYLON;
  87734. (function (BABYLON) {
  87735. /**
  87736. * Background material defines definition.
  87737. * @ignore Mainly internal Use
  87738. */
  87739. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  87740. __extends(BackgroundMaterialDefines, _super);
  87741. /**
  87742. * Constructor of the defines.
  87743. */
  87744. function BackgroundMaterialDefines() {
  87745. var _this = _super.call(this) || this;
  87746. /**
  87747. * True if the diffuse texture is in use.
  87748. */
  87749. _this.DIFFUSE = false;
  87750. /**
  87751. * The direct UV channel to use.
  87752. */
  87753. _this.DIFFUSEDIRECTUV = 0;
  87754. /**
  87755. * True if the diffuse texture is in gamma space.
  87756. */
  87757. _this.GAMMADIFFUSE = false;
  87758. /**
  87759. * True if the diffuse texture has opacity in the alpha channel.
  87760. */
  87761. _this.DIFFUSEHASALPHA = false;
  87762. /**
  87763. * True if you want the material to fade to transparent at grazing angle.
  87764. */
  87765. _this.OPACITYFRESNEL = false;
  87766. /**
  87767. * True if an extra blur needs to be added in the reflection.
  87768. */
  87769. _this.REFLECTIONBLUR = false;
  87770. /**
  87771. * True if you want the material to fade to reflection at grazing angle.
  87772. */
  87773. _this.REFLECTIONFRESNEL = false;
  87774. /**
  87775. * True if you want the material to falloff as far as you move away from the scene center.
  87776. */
  87777. _this.REFLECTIONFALLOFF = false;
  87778. /**
  87779. * False if the current Webgl implementation does not support the texture lod extension.
  87780. */
  87781. _this.TEXTURELODSUPPORT = false;
  87782. /**
  87783. * True to ensure the data are premultiplied.
  87784. */
  87785. _this.PREMULTIPLYALPHA = false;
  87786. /**
  87787. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  87788. */
  87789. _this.USERGBCOLOR = false;
  87790. /**
  87791. * True to add noise in order to reduce the banding effect.
  87792. */
  87793. _this.NOISE = false;
  87794. /**
  87795. * is the reflection texture in BGR color scheme?
  87796. * Mainly used to solve a bug in ios10 video tag
  87797. */
  87798. _this.REFLECTIONBGR = false;
  87799. _this.IMAGEPROCESSING = false;
  87800. _this.VIGNETTE = false;
  87801. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87802. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87803. _this.TONEMAPPING = false;
  87804. _this.CONTRAST = false;
  87805. _this.COLORCURVES = false;
  87806. _this.COLORGRADING = false;
  87807. _this.COLORGRADING3D = false;
  87808. _this.SAMPLER3DGREENDEPTH = false;
  87809. _this.SAMPLER3DBGRMAP = false;
  87810. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87811. _this.EXPOSURE = false;
  87812. // Reflection.
  87813. _this.REFLECTION = false;
  87814. _this.REFLECTIONMAP_3D = false;
  87815. _this.REFLECTIONMAP_SPHERICAL = false;
  87816. _this.REFLECTIONMAP_PLANAR = false;
  87817. _this.REFLECTIONMAP_CUBIC = false;
  87818. _this.REFLECTIONMAP_PROJECTION = false;
  87819. _this.REFLECTIONMAP_SKYBOX = false;
  87820. _this.REFLECTIONMAP_EXPLICIT = false;
  87821. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87822. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87823. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87824. _this.INVERTCUBICMAP = false;
  87825. _this.REFLECTIONMAP_OPPOSITEZ = false;
  87826. _this.LODINREFLECTIONALPHA = false;
  87827. _this.GAMMAREFLECTION = false;
  87828. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  87829. // Default BJS.
  87830. _this.MAINUV1 = false;
  87831. _this.MAINUV2 = false;
  87832. _this.UV1 = false;
  87833. _this.UV2 = false;
  87834. _this.CLIPPLANE = false;
  87835. _this.POINTSIZE = false;
  87836. _this.FOG = false;
  87837. _this.NORMAL = false;
  87838. _this.NUM_BONE_INFLUENCERS = 0;
  87839. _this.BonesPerMesh = 0;
  87840. _this.INSTANCES = false;
  87841. _this.SHADOWFLOAT = false;
  87842. _this.rebuild();
  87843. return _this;
  87844. }
  87845. return BackgroundMaterialDefines;
  87846. }(BABYLON.MaterialDefines));
  87847. /**
  87848. * Background material used to create an efficient environement around your scene.
  87849. */
  87850. var BackgroundMaterial = /** @class */ (function (_super) {
  87851. __extends(BackgroundMaterial, _super);
  87852. /**
  87853. * Instantiates a Background Material in the given scene
  87854. * @param name The friendly name of the material
  87855. * @param scene The scene to add the material to
  87856. */
  87857. function BackgroundMaterial(name, scene) {
  87858. var _this = _super.call(this, name, scene) || this;
  87859. /**
  87860. * Key light Color (multiply against the R channel of the environement texture)
  87861. */
  87862. _this.primaryColor = BABYLON.Color3.White();
  87863. /**
  87864. * Key light Level (allowing HDR output of the background)
  87865. */
  87866. _this.primaryLevel = 1;
  87867. /**
  87868. * Secondary light Color (multiply against the G channel of the environement texture)
  87869. */
  87870. _this.secondaryColor = BABYLON.Color3.Gray();
  87871. /**
  87872. * Secondary light Level (allowing HDR output of the background)
  87873. */
  87874. _this.secondaryLevel = 1;
  87875. /**
  87876. * Tertiary light Color (multiply against the B channel of the environement texture)
  87877. */
  87878. _this.tertiaryColor = BABYLON.Color3.Black();
  87879. /**
  87880. * Tertiary light Level (allowing HDR output of the background)
  87881. */
  87882. _this.tertiaryLevel = 1;
  87883. /**
  87884. * Reflection Texture used in the material.
  87885. * Should be author in a specific way for the best result (refer to the documentation).
  87886. */
  87887. _this.reflectionTexture = null;
  87888. /**
  87889. * Reflection Texture level of blur.
  87890. *
  87891. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87892. * texture twice.
  87893. */
  87894. _this.reflectionBlur = 0;
  87895. /**
  87896. * Diffuse Texture used in the material.
  87897. * Should be author in a specific way for the best result (refer to the documentation).
  87898. */
  87899. _this.diffuseTexture = null;
  87900. _this._shadowLights = null;
  87901. /**
  87902. * Specify the list of lights casting shadow on the material.
  87903. * All scene shadow lights will be included if null.
  87904. */
  87905. _this.shadowLights = null;
  87906. /**
  87907. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87908. * soft lighting on the background.
  87909. */
  87910. _this.shadowBlurScale = 1;
  87911. /**
  87912. * Helps adjusting the shadow to a softer level if required.
  87913. * 0 means black shadows and 1 means no shadows.
  87914. */
  87915. _this.shadowLevel = 0;
  87916. /**
  87917. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87918. * It is usually zero but might be interesting to modify according to your setup.
  87919. */
  87920. _this.sceneCenter = BABYLON.Vector3.Zero();
  87921. /**
  87922. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87923. * This helps ensuring a nice transition when the camera goes under the ground.
  87924. */
  87925. _this.opacityFresnel = true;
  87926. /**
  87927. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87928. * This helps adding a mirror texture on the ground.
  87929. */
  87930. _this.reflectionFresnel = false;
  87931. /**
  87932. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87933. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87934. */
  87935. _this.reflectionFalloffDistance = 0.0;
  87936. /**
  87937. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87938. */
  87939. _this.reflectionAmount = 1.0;
  87940. /**
  87941. * This specifies the weight of the reflection at grazing angle.
  87942. */
  87943. _this.reflectionReflectance0 = 0.05;
  87944. /**
  87945. * This specifies the weight of the reflection at a perpendicular point of view.
  87946. */
  87947. _this.reflectionReflectance90 = 0.5;
  87948. /**
  87949. * Helps to directly use the maps channels instead of their level.
  87950. */
  87951. _this.useRGBColor = true;
  87952. /**
  87953. * This helps reducing the banding effect that could occur on the background.
  87954. */
  87955. _this.enableNoise = false;
  87956. _this._fovMultiplier = 1.0;
  87957. /**
  87958. * Enable the FOV adjustment feature controlled by fovMultiplier.
  87959. * @type {boolean}
  87960. */
  87961. _this.useEquirectangularFOV = false;
  87962. _this._maxSimultaneousLights = 4;
  87963. /**
  87964. * Number of Simultaneous lights allowed on the material.
  87965. */
  87966. _this.maxSimultaneousLights = 4;
  87967. /**
  87968. * Keep track of the image processing observer to allow dispose and replace.
  87969. */
  87970. _this._imageProcessingObserver = null;
  87971. /**
  87972. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  87973. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  87974. */
  87975. _this.switchToBGR = false;
  87976. // Temp values kept as cache in the material.
  87977. _this._renderTargets = new BABYLON.SmartArray(16);
  87978. _this._reflectionControls = BABYLON.Vector4.Zero();
  87979. // Setup the default processing configuration to the scene.
  87980. _this._attachImageProcessingConfiguration(null);
  87981. _this.getRenderTargetTextures = function () {
  87982. _this._renderTargets.reset();
  87983. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  87984. _this._renderTargets.push(_this._diffuseTexture);
  87985. }
  87986. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  87987. _this._renderTargets.push(_this._reflectionTexture);
  87988. }
  87989. return _this._renderTargets;
  87990. };
  87991. return _this;
  87992. }
  87993. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  87994. /**
  87995. * Sets the reflection reflectance fresnel values according to the default standard
  87996. * empirically know to work well :-)
  87997. */
  87998. set: function (value) {
  87999. var reflectionWeight = value;
  88000. if (reflectionWeight < 0.5) {
  88001. reflectionWeight = reflectionWeight * 2.0;
  88002. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88003. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88004. }
  88005. else {
  88006. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88007. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88008. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88009. }
  88010. },
  88011. enumerable: true,
  88012. configurable: true
  88013. });
  88014. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88015. /**
  88016. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88017. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88018. * Recommended to be keep at 1.0 except for special cases.
  88019. */
  88020. get: function () {
  88021. return this._fovMultiplier;
  88022. },
  88023. set: function (value) {
  88024. if (isNaN(value)) {
  88025. value = 1.0;
  88026. }
  88027. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88028. },
  88029. enumerable: true,
  88030. configurable: true
  88031. });
  88032. /**
  88033. * Attaches a new image processing configuration to the PBR Material.
  88034. * @param configuration (if null the scene configuration will be use)
  88035. */
  88036. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88037. var _this = this;
  88038. if (configuration === this._imageProcessingConfiguration) {
  88039. return;
  88040. }
  88041. // Detaches observer.
  88042. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88043. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88044. }
  88045. // Pick the scene configuration if needed.
  88046. if (!configuration) {
  88047. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88048. }
  88049. else {
  88050. this._imageProcessingConfiguration = configuration;
  88051. }
  88052. // Attaches observer.
  88053. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88054. _this._markAllSubMeshesAsImageProcessingDirty();
  88055. });
  88056. };
  88057. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88058. /**
  88059. * Gets the image processing configuration used either in this material.
  88060. */
  88061. get: function () {
  88062. return this._imageProcessingConfiguration;
  88063. },
  88064. /**
  88065. * Sets the Default image processing configuration used either in the this material.
  88066. *
  88067. * If sets to null, the scene one is in use.
  88068. */
  88069. set: function (value) {
  88070. this._attachImageProcessingConfiguration(value);
  88071. // Ensure the effect will be rebuilt.
  88072. this._markAllSubMeshesAsTexturesDirty();
  88073. },
  88074. enumerable: true,
  88075. configurable: true
  88076. });
  88077. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88078. /**
  88079. * Gets wether the color curves effect is enabled.
  88080. */
  88081. get: function () {
  88082. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88083. },
  88084. /**
  88085. * Sets wether the color curves effect is enabled.
  88086. */
  88087. set: function (value) {
  88088. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88089. },
  88090. enumerable: true,
  88091. configurable: true
  88092. });
  88093. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88094. /**
  88095. * Gets wether the color grading effect is enabled.
  88096. */
  88097. get: function () {
  88098. return this.imageProcessingConfiguration.colorGradingEnabled;
  88099. },
  88100. /**
  88101. * Gets wether the color grading effect is enabled.
  88102. */
  88103. set: function (value) {
  88104. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88105. },
  88106. enumerable: true,
  88107. configurable: true
  88108. });
  88109. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88110. /**
  88111. * Gets wether tonemapping is enabled or not.
  88112. */
  88113. get: function () {
  88114. return this._imageProcessingConfiguration.toneMappingEnabled;
  88115. },
  88116. /**
  88117. * Sets wether tonemapping is enabled or not
  88118. */
  88119. set: function (value) {
  88120. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88121. },
  88122. enumerable: true,
  88123. configurable: true
  88124. });
  88125. ;
  88126. ;
  88127. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88128. /**
  88129. * The camera exposure used on this material.
  88130. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88131. * This corresponds to a photographic exposure.
  88132. */
  88133. get: function () {
  88134. return this._imageProcessingConfiguration.exposure;
  88135. },
  88136. /**
  88137. * The camera exposure used on this material.
  88138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88139. * This corresponds to a photographic exposure.
  88140. */
  88141. set: function (value) {
  88142. this._imageProcessingConfiguration.exposure = value;
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. ;
  88148. ;
  88149. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88150. /**
  88151. * Gets The camera contrast used on this material.
  88152. */
  88153. get: function () {
  88154. return this._imageProcessingConfiguration.contrast;
  88155. },
  88156. /**
  88157. * Sets The camera contrast used on this material.
  88158. */
  88159. set: function (value) {
  88160. this._imageProcessingConfiguration.contrast = value;
  88161. },
  88162. enumerable: true,
  88163. configurable: true
  88164. });
  88165. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88166. /**
  88167. * Gets the Color Grading 2D Lookup Texture.
  88168. */
  88169. get: function () {
  88170. return this._imageProcessingConfiguration.colorGradingTexture;
  88171. },
  88172. /**
  88173. * Sets the Color Grading 2D Lookup Texture.
  88174. */
  88175. set: function (value) {
  88176. this.imageProcessingConfiguration.colorGradingTexture = value;
  88177. },
  88178. enumerable: true,
  88179. configurable: true
  88180. });
  88181. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88182. /**
  88183. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88184. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88185. * 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;
  88186. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88187. */
  88188. get: function () {
  88189. return this.imageProcessingConfiguration.colorCurves;
  88190. },
  88191. /**
  88192. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88193. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88194. * 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;
  88195. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88196. */
  88197. set: function (value) {
  88198. this.imageProcessingConfiguration.colorCurves = value;
  88199. },
  88200. enumerable: true,
  88201. configurable: true
  88202. });
  88203. /**
  88204. * The entire material has been created in order to prevent overdraw.
  88205. * @returns false
  88206. */
  88207. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88208. return true;
  88209. };
  88210. /**
  88211. * The entire material has been created in order to prevent overdraw.
  88212. * @returns true if blending is enable
  88213. */
  88214. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88215. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88216. };
  88217. /**
  88218. * Checks wether the material is ready to be rendered for a given mesh.
  88219. * @param mesh The mesh to render
  88220. * @param subMesh The submesh to check against
  88221. * @param useInstances Specify wether or not the material is used with instances
  88222. * @returns true if all the dependencies are ready (Textures, Effects...)
  88223. */
  88224. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88225. var _this = this;
  88226. if (useInstances === void 0) { useInstances = false; }
  88227. if (subMesh.effect && this.isFrozen) {
  88228. if (this._wasPreviouslyReady) {
  88229. return true;
  88230. }
  88231. }
  88232. if (!subMesh._materialDefines) {
  88233. subMesh._materialDefines = new BackgroundMaterialDefines();
  88234. }
  88235. var scene = this.getScene();
  88236. var defines = subMesh._materialDefines;
  88237. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88238. if (defines._renderId === scene.getRenderId()) {
  88239. return true;
  88240. }
  88241. }
  88242. var engine = scene.getEngine();
  88243. // Lights
  88244. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88245. defines._needNormals = true;
  88246. // Textures
  88247. if (defines._areTexturesDirty) {
  88248. defines._needUVs = false;
  88249. if (scene.texturesEnabled) {
  88250. if (scene.getEngine().getCaps().textureLOD) {
  88251. defines.TEXTURELODSUPPORT = true;
  88252. }
  88253. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88254. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88255. return false;
  88256. }
  88257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88258. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88259. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88260. defines.OPACITYFRESNEL = this._opacityFresnel;
  88261. }
  88262. else {
  88263. defines.DIFFUSE = false;
  88264. defines.DIFFUSEHASALPHA = false;
  88265. defines.GAMMADIFFUSE = false;
  88266. defines.OPACITYFRESNEL = false;
  88267. }
  88268. var reflectionTexture = this._reflectionTexture;
  88269. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88270. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88271. return false;
  88272. }
  88273. defines.REFLECTION = true;
  88274. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88275. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88276. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88277. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88278. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88279. defines.REFLECTIONBGR = this.switchToBGR;
  88280. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88281. defines.INVERTCUBICMAP = true;
  88282. }
  88283. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88284. switch (reflectionTexture.coordinatesMode) {
  88285. case BABYLON.Texture.CUBIC_MODE:
  88286. case BABYLON.Texture.INVCUBIC_MODE:
  88287. defines.REFLECTIONMAP_CUBIC = true;
  88288. break;
  88289. case BABYLON.Texture.EXPLICIT_MODE:
  88290. defines.REFLECTIONMAP_EXPLICIT = true;
  88291. break;
  88292. case BABYLON.Texture.PLANAR_MODE:
  88293. defines.REFLECTIONMAP_PLANAR = true;
  88294. break;
  88295. case BABYLON.Texture.PROJECTION_MODE:
  88296. defines.REFLECTIONMAP_PROJECTION = true;
  88297. break;
  88298. case BABYLON.Texture.SKYBOX_MODE:
  88299. defines.REFLECTIONMAP_SKYBOX = true;
  88300. break;
  88301. case BABYLON.Texture.SPHERICAL_MODE:
  88302. defines.REFLECTIONMAP_SPHERICAL = true;
  88303. break;
  88304. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88305. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88306. break;
  88307. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88308. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88309. break;
  88310. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88311. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88312. break;
  88313. }
  88314. if (this.reflectionFresnel) {
  88315. defines.REFLECTIONFRESNEL = true;
  88316. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88317. this._reflectionControls.x = this.reflectionAmount;
  88318. this._reflectionControls.y = this.reflectionReflectance0;
  88319. this._reflectionControls.z = this.reflectionReflectance90;
  88320. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88321. }
  88322. else {
  88323. defines.REFLECTIONFRESNEL = false;
  88324. defines.REFLECTIONFALLOFF = false;
  88325. }
  88326. }
  88327. else {
  88328. defines.REFLECTION = false;
  88329. defines.REFLECTIONFALLOFF = false;
  88330. defines.REFLECTIONBLUR = false;
  88331. defines.REFLECTIONMAP_3D = false;
  88332. defines.REFLECTIONMAP_SPHERICAL = false;
  88333. defines.REFLECTIONMAP_PLANAR = false;
  88334. defines.REFLECTIONMAP_CUBIC = false;
  88335. defines.REFLECTIONMAP_PROJECTION = false;
  88336. defines.REFLECTIONMAP_SKYBOX = false;
  88337. defines.REFLECTIONMAP_EXPLICIT = false;
  88338. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88339. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88340. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88341. defines.INVERTCUBICMAP = false;
  88342. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88343. defines.LODINREFLECTIONALPHA = false;
  88344. defines.GAMMAREFLECTION = false;
  88345. }
  88346. }
  88347. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88348. defines.USERGBCOLOR = this._useRGBColor;
  88349. defines.NOISE = this._enableNoise;
  88350. }
  88351. if (defines._areImageProcessingDirty) {
  88352. if (!this._imageProcessingConfiguration.isReady()) {
  88353. return false;
  88354. }
  88355. this._imageProcessingConfiguration.prepareDefines(defines);
  88356. }
  88357. // Misc.
  88358. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88359. // Values that need to be evaluated on every frame
  88360. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88361. // Attribs
  88362. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88363. if (mesh) {
  88364. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88365. mesh.createNormals(true);
  88366. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88367. }
  88368. }
  88369. }
  88370. // Get correct effect
  88371. if (defines.isDirty) {
  88372. defines.markAsProcessed();
  88373. scene.resetCachedMaterial();
  88374. // Fallbacks
  88375. var fallbacks = new BABYLON.EffectFallbacks();
  88376. if (defines.FOG) {
  88377. fallbacks.addFallback(0, "FOG");
  88378. }
  88379. if (defines.POINTSIZE) {
  88380. fallbacks.addFallback(1, "POINTSIZE");
  88381. }
  88382. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88383. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88384. fallbacks.addCPUSkinningFallback(0, mesh);
  88385. }
  88386. //Attributes
  88387. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88388. if (defines.NORMAL) {
  88389. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88390. }
  88391. if (defines.UV1) {
  88392. attribs.push(BABYLON.VertexBuffer.UVKind);
  88393. }
  88394. if (defines.UV2) {
  88395. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88396. }
  88397. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88398. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88399. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88400. "vFogInfos", "vFogColor", "pointSize",
  88401. "vClipPlane", "mBones",
  88402. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88403. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88404. "shadowLevel", "alpha",
  88405. "vBackgroundCenter", "vReflectionControl",
  88406. "vDiffuseInfos", "diffuseMatrix",
  88407. ];
  88408. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88409. var uniformBuffers = ["Material", "Scene"];
  88410. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88411. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88412. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88413. uniformsNames: uniforms,
  88414. uniformBuffersNames: uniformBuffers,
  88415. samplers: samplers,
  88416. defines: defines,
  88417. maxSimultaneousLights: this._maxSimultaneousLights
  88418. });
  88419. var onCompiled = function (effect) {
  88420. if (_this.onCompiled) {
  88421. _this.onCompiled(effect);
  88422. }
  88423. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88424. };
  88425. var join = defines.toString();
  88426. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88427. attributes: attribs,
  88428. uniformsNames: uniforms,
  88429. uniformBuffersNames: uniformBuffers,
  88430. samplers: samplers,
  88431. defines: join,
  88432. fallbacks: fallbacks,
  88433. onCompiled: onCompiled,
  88434. onError: this.onError,
  88435. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88436. }, engine), defines);
  88437. this.buildUniformLayout();
  88438. }
  88439. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88440. return false;
  88441. }
  88442. defines._renderId = scene.getRenderId();
  88443. this._wasPreviouslyReady = true;
  88444. return true;
  88445. };
  88446. /**
  88447. * Build the uniform buffer used in the material.
  88448. */
  88449. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88450. // Order is important !
  88451. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88452. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88453. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88454. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88455. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88456. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88457. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88458. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88459. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88460. this._uniformBuffer.addUniform("pointSize", 1);
  88461. this._uniformBuffer.addUniform("shadowLevel", 1);
  88462. this._uniformBuffer.addUniform("alpha", 1);
  88463. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88464. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88465. this._uniformBuffer.create();
  88466. };
  88467. /**
  88468. * Unbind the material.
  88469. */
  88470. BackgroundMaterial.prototype.unbind = function () {
  88471. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88472. this._uniformBuffer.setTexture("diffuseSampler", null);
  88473. }
  88474. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88475. this._uniformBuffer.setTexture("reflectionSampler", null);
  88476. }
  88477. _super.prototype.unbind.call(this);
  88478. };
  88479. /**
  88480. * Bind only the world matrix to the material.
  88481. * @param world The world matrix to bind.
  88482. */
  88483. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88484. this._activeEffect.setMatrix("world", world);
  88485. };
  88486. /**
  88487. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88488. * @param world The world matrix to bind.
  88489. * @param subMesh The submesh to bind for.
  88490. */
  88491. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88492. var scene = this.getScene();
  88493. var defines = subMesh._materialDefines;
  88494. if (!defines) {
  88495. return;
  88496. }
  88497. var effect = subMesh.effect;
  88498. if (!effect) {
  88499. return;
  88500. }
  88501. this._activeEffect = effect;
  88502. // Matrices
  88503. this.bindOnlyWorldMatrix(world);
  88504. // Bones
  88505. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88506. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88507. if (mustRebind) {
  88508. this._uniformBuffer.bindToEffect(effect, "Material");
  88509. this.bindViewProjection(effect);
  88510. var reflectionTexture = this._reflectionTexture;
  88511. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88512. // Texture uniforms
  88513. if (scene.texturesEnabled) {
  88514. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88515. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88516. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88517. }
  88518. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88519. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88520. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88521. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88522. }
  88523. }
  88524. if (this.shadowLevel > 0) {
  88525. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88526. }
  88527. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88528. // Point size
  88529. if (this.pointsCloud) {
  88530. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88531. }
  88532. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88533. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88534. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88535. }
  88536. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88537. // Textures
  88538. if (scene.texturesEnabled) {
  88539. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88540. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88541. }
  88542. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88543. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88544. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88545. }
  88546. else if (!defines.REFLECTIONBLUR) {
  88547. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88548. }
  88549. else {
  88550. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88551. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88552. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88553. }
  88554. if (defines.REFLECTIONFRESNEL) {
  88555. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88556. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88557. }
  88558. }
  88559. }
  88560. // Clip plane
  88561. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88562. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88563. }
  88564. if (mustRebind || !this.isFrozen) {
  88565. if (scene.lightsEnabled) {
  88566. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88567. }
  88568. // View
  88569. this.bindView(effect);
  88570. // Fog
  88571. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88572. // image processing
  88573. this._imageProcessingConfiguration.bind(this._activeEffect);
  88574. }
  88575. this._uniformBuffer.update();
  88576. this._afterBind(mesh);
  88577. };
  88578. /**
  88579. * Dispose the material.
  88580. * @param forceDisposeEffect Force disposal of the associated effect.
  88581. * @param forceDisposeTextures Force disposal of the associated textures.
  88582. */
  88583. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88584. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88585. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88586. if (forceDisposeTextures) {
  88587. if (this.diffuseTexture) {
  88588. this.diffuseTexture.dispose();
  88589. }
  88590. if (this.reflectionTexture) {
  88591. this.reflectionTexture.dispose();
  88592. }
  88593. }
  88594. this._renderTargets.dispose();
  88595. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88596. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88597. }
  88598. _super.prototype.dispose.call(this, forceDisposeEffect);
  88599. };
  88600. /**
  88601. * Clones the material.
  88602. * @param name The cloned name.
  88603. * @returns The cloned material.
  88604. */
  88605. BackgroundMaterial.prototype.clone = function (name) {
  88606. var _this = this;
  88607. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88608. };
  88609. /**
  88610. * Serializes the current material to its JSON representation.
  88611. * @returns The JSON representation.
  88612. */
  88613. BackgroundMaterial.prototype.serialize = function () {
  88614. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88615. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88616. return serializationObject;
  88617. };
  88618. /**
  88619. * Gets the class name of the material
  88620. * @returns "BackgroundMaterial"
  88621. */
  88622. BackgroundMaterial.prototype.getClassName = function () {
  88623. return "BackgroundMaterial";
  88624. };
  88625. /**
  88626. * Parse a JSON input to create back a background material.
  88627. * @param source The JSON data to parse
  88628. * @param scene The scene to create the parsed material in
  88629. * @param rootUrl The root url of the assets the material depends upon
  88630. * @returns the instantiated BackgroundMaterial.
  88631. */
  88632. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88633. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88634. };
  88635. /**
  88636. * Standard reflectance value at parallel view angle.
  88637. */
  88638. BackgroundMaterial.StandardReflectance0 = 0.05;
  88639. /**
  88640. * Standard reflectance value at grazing angle.
  88641. */
  88642. BackgroundMaterial.StandardReflectance90 = 0.5;
  88643. __decorate([
  88644. BABYLON.serializeAsColor3()
  88645. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88646. __decorate([
  88647. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88648. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88649. __decorate([
  88650. BABYLON.serialize()
  88651. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88652. __decorate([
  88653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88654. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88655. __decorate([
  88656. BABYLON.serializeAsColor3()
  88657. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88658. __decorate([
  88659. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88660. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88661. __decorate([
  88662. BABYLON.serialize()
  88663. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88664. __decorate([
  88665. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88666. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88667. __decorate([
  88668. BABYLON.serializeAsColor3()
  88669. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88670. __decorate([
  88671. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88672. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88673. __decorate([
  88674. BABYLON.serialize()
  88675. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88676. __decorate([
  88677. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88678. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88679. __decorate([
  88680. BABYLON.serializeAsTexture()
  88681. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88682. __decorate([
  88683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88684. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88685. __decorate([
  88686. BABYLON.serialize()
  88687. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88688. __decorate([
  88689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88690. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88691. __decorate([
  88692. BABYLON.serializeAsTexture()
  88693. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88694. __decorate([
  88695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88696. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88697. __decorate([
  88698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88699. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88700. __decorate([
  88701. BABYLON.serialize()
  88702. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88703. __decorate([
  88704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88705. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88706. __decorate([
  88707. BABYLON.serialize()
  88708. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88709. __decorate([
  88710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88711. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88712. __decorate([
  88713. BABYLON.serializeAsVector3()
  88714. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88715. __decorate([
  88716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88717. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88718. __decorate([
  88719. BABYLON.serialize()
  88720. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88721. __decorate([
  88722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88723. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  88724. __decorate([
  88725. BABYLON.serialize()
  88726. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  88727. __decorate([
  88728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88729. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  88730. __decorate([
  88731. BABYLON.serialize()
  88732. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  88733. __decorate([
  88734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88735. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  88736. __decorate([
  88737. BABYLON.serialize()
  88738. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  88739. __decorate([
  88740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88741. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  88742. __decorate([
  88743. BABYLON.serialize()
  88744. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  88745. __decorate([
  88746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88747. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  88748. __decorate([
  88749. BABYLON.serialize()
  88750. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  88751. __decorate([
  88752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88753. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  88754. __decorate([
  88755. BABYLON.serialize()
  88756. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  88757. __decorate([
  88758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88759. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  88760. __decorate([
  88761. BABYLON.serialize()
  88762. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  88763. __decorate([
  88764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88765. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  88766. __decorate([
  88767. BABYLON.serialize()
  88768. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  88769. __decorate([
  88770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88771. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  88772. __decorate([
  88773. BABYLON.serializeAsImageProcessingConfiguration()
  88774. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  88775. return BackgroundMaterial;
  88776. }(BABYLON.PushMaterial));
  88777. BABYLON.BackgroundMaterial = BackgroundMaterial;
  88778. })(BABYLON || (BABYLON = {}));
  88779. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  88780. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88781. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88782. s = arguments[i];
  88783. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88784. t[p] = s[p];
  88785. }
  88786. return t;
  88787. };
  88788. var BABYLON;
  88789. (function (BABYLON) {
  88790. /**
  88791. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  88792. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  88793. * It also helps with the default setup of your imageProcessing configuration.
  88794. */
  88795. var EnvironmentHelper = /** @class */ (function () {
  88796. /**
  88797. * constructor
  88798. * @param options
  88799. * @param scene The scene to add the material to
  88800. */
  88801. function EnvironmentHelper(options, scene) {
  88802. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  88803. this._scene = scene;
  88804. this._setupBackground();
  88805. this._setupImageProcessing();
  88806. }
  88807. /**
  88808. * Creates the default options for the helper.
  88809. */
  88810. EnvironmentHelper._getDefaultOptions = function () {
  88811. return {
  88812. createGround: true,
  88813. groundSize: 15,
  88814. groundTexture: this._groundTextureCDNUrl,
  88815. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88816. groundOpacity: 0.9,
  88817. enableGroundShadow: true,
  88818. groundShadowLevel: 0.5,
  88819. enableGroundMirror: false,
  88820. groundMirrorSizeRatio: 0.3,
  88821. groundMirrorBlurKernel: 64,
  88822. groundMirrorAmount: 1,
  88823. groundMirrorFresnelWeight: 1,
  88824. groundMirrorFallOffDistance: 0,
  88825. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  88826. groundYBias: 0.00001,
  88827. createSkybox: true,
  88828. skyboxSize: 20,
  88829. skyboxTexture: this._skyboxTextureCDNUrl,
  88830. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88831. backgroundYRotation: 0,
  88832. sizeAuto: true,
  88833. rootPosition: BABYLON.Vector3.Zero(),
  88834. setupImageProcessing: true,
  88835. environmentTexture: this._environmentTextureCDNUrl,
  88836. cameraExposure: 0.8,
  88837. cameraContrast: 1.2,
  88838. toneMappingEnabled: true,
  88839. };
  88840. };
  88841. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88842. /**
  88843. * Gets the root mesh created by the helper.
  88844. */
  88845. get: function () {
  88846. return this._rootMesh;
  88847. },
  88848. enumerable: true,
  88849. configurable: true
  88850. });
  88851. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88852. /**
  88853. * Gets the skybox created by the helper.
  88854. */
  88855. get: function () {
  88856. return this._skybox;
  88857. },
  88858. enumerable: true,
  88859. configurable: true
  88860. });
  88861. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88862. /**
  88863. * Gets the skybox texture created by the helper.
  88864. */
  88865. get: function () {
  88866. return this._skyboxTexture;
  88867. },
  88868. enumerable: true,
  88869. configurable: true
  88870. });
  88871. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88872. /**
  88873. * Gets the skybox material created by the helper.
  88874. */
  88875. get: function () {
  88876. return this._skyboxMaterial;
  88877. },
  88878. enumerable: true,
  88879. configurable: true
  88880. });
  88881. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88882. /**
  88883. * Gets the ground mesh created by the helper.
  88884. */
  88885. get: function () {
  88886. return this._ground;
  88887. },
  88888. enumerable: true,
  88889. configurable: true
  88890. });
  88891. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88892. /**
  88893. * Gets the ground texture created by the helper.
  88894. */
  88895. get: function () {
  88896. return this._groundTexture;
  88897. },
  88898. enumerable: true,
  88899. configurable: true
  88900. });
  88901. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88902. /**
  88903. * Gets the ground mirror created by the helper.
  88904. */
  88905. get: function () {
  88906. return this._groundMirror;
  88907. },
  88908. enumerable: true,
  88909. configurable: true
  88910. });
  88911. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88912. /**
  88913. * Gets the ground mirror render list to helps pushing the meshes
  88914. * you wish in the ground reflection.
  88915. */
  88916. get: function () {
  88917. if (this._groundMirror) {
  88918. return this._groundMirror.renderList;
  88919. }
  88920. return null;
  88921. },
  88922. enumerable: true,
  88923. configurable: true
  88924. });
  88925. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88926. /**
  88927. * Gets the ground material created by the helper.
  88928. */
  88929. get: function () {
  88930. return this._groundMaterial;
  88931. },
  88932. enumerable: true,
  88933. configurable: true
  88934. });
  88935. /**
  88936. * Updates the background according to the new options
  88937. * @param options
  88938. */
  88939. EnvironmentHelper.prototype.updateOptions = function (options) {
  88940. var newOptions = __assign({}, this._options, options);
  88941. if (this._ground && !newOptions.createGround) {
  88942. this._ground.dispose();
  88943. this._ground = null;
  88944. }
  88945. if (this._groundMaterial && !newOptions.createGround) {
  88946. this._groundMaterial.dispose();
  88947. this._groundMaterial = null;
  88948. }
  88949. if (this._groundTexture) {
  88950. if (this._options.groundTexture != newOptions.groundTexture) {
  88951. this._groundTexture.dispose();
  88952. this._groundTexture = null;
  88953. }
  88954. }
  88955. if (this._skybox && !newOptions.createSkybox) {
  88956. this._skybox.dispose();
  88957. this._skybox = null;
  88958. }
  88959. if (this._skyboxMaterial && !newOptions.createSkybox) {
  88960. this._skyboxMaterial.dispose();
  88961. this._skyboxMaterial = null;
  88962. }
  88963. if (this._skyboxTexture) {
  88964. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  88965. this._skyboxTexture.dispose();
  88966. this._skyboxTexture = null;
  88967. }
  88968. }
  88969. if (this._groundMirror && !newOptions.enableGroundMirror) {
  88970. this._groundMirror.dispose();
  88971. this._groundMirror = null;
  88972. }
  88973. if (this._scene.environmentTexture) {
  88974. if (this._options.environmentTexture != newOptions.environmentTexture) {
  88975. this._scene.environmentTexture.dispose();
  88976. }
  88977. }
  88978. this._options = newOptions;
  88979. this._setupBackground();
  88980. this._setupImageProcessing();
  88981. };
  88982. /**
  88983. * Sets the primary color of all the available elements.
  88984. * @param color
  88985. */
  88986. EnvironmentHelper.prototype.setMainColor = function (color) {
  88987. if (this.groundMaterial) {
  88988. this.groundMaterial.primaryColor = color;
  88989. }
  88990. if (this.skyboxMaterial) {
  88991. this.skyboxMaterial.primaryColor = color;
  88992. }
  88993. if (this.groundMirror) {
  88994. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  88995. }
  88996. };
  88997. /**
  88998. * Setup the image processing according to the specified options.
  88999. */
  89000. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89001. if (this._options.setupImageProcessing) {
  89002. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89003. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89004. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89005. this._setupEnvironmentTexture();
  89006. }
  89007. };
  89008. /**
  89009. * Setup the environment texture according to the specified options.
  89010. */
  89011. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89012. if (this._scene.environmentTexture) {
  89013. return;
  89014. }
  89015. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89016. this._scene.environmentTexture = this._options.environmentTexture;
  89017. return;
  89018. }
  89019. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89020. this._scene.environmentTexture = environmentTexture;
  89021. };
  89022. /**
  89023. * Setup the background according to the specified options.
  89024. */
  89025. EnvironmentHelper.prototype._setupBackground = function () {
  89026. if (!this._rootMesh) {
  89027. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89028. }
  89029. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89030. var sceneSize = this._getSceneSize();
  89031. if (this._options.createGround) {
  89032. this._setupGround(sceneSize);
  89033. this._setupGroundMaterial();
  89034. this._setupGroundDiffuseTexture();
  89035. if (this._options.enableGroundMirror) {
  89036. this._setupGroundMirrorTexture(sceneSize);
  89037. }
  89038. this._setupMirrorInGroundMaterial();
  89039. }
  89040. if (this._options.createSkybox) {
  89041. this._setupSkybox(sceneSize);
  89042. this._setupSkyboxMaterial();
  89043. this._setupSkyboxReflectionTexture();
  89044. }
  89045. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89046. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89047. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89048. };
  89049. /**
  89050. * Get the scene sizes according to the setup.
  89051. */
  89052. EnvironmentHelper.prototype._getSceneSize = function () {
  89053. var _this = this;
  89054. var groundSize = this._options.groundSize;
  89055. var skyboxSize = this._options.skyboxSize;
  89056. var rootPosition = this._options.rootPosition;
  89057. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89058. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89059. }
  89060. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89061. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89062. });
  89063. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89064. if (this._options.sizeAuto) {
  89065. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89066. this._scene.activeCamera.upperRadiusLimit) {
  89067. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89068. skyboxSize = groundSize;
  89069. }
  89070. var sceneDiagonalLenght = sceneDiagonal.length();
  89071. if (sceneDiagonalLenght > groundSize) {
  89072. groundSize = sceneDiagonalLenght * 2;
  89073. skyboxSize = groundSize;
  89074. }
  89075. // 10 % bigger.
  89076. groundSize *= 1.1;
  89077. skyboxSize *= 1.5;
  89078. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89079. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89080. }
  89081. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89082. };
  89083. /**
  89084. * Setup the ground according to the specified options.
  89085. */
  89086. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89087. var _this = this;
  89088. if (!this._ground) {
  89089. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89090. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89091. this._ground.parent = this._rootMesh;
  89092. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89093. }
  89094. this._ground.receiveShadows = this._options.enableGroundShadow;
  89095. };
  89096. /**
  89097. * Setup the ground material according to the specified options.
  89098. */
  89099. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89100. if (!this._groundMaterial) {
  89101. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89102. }
  89103. this._groundMaterial.alpha = this._options.groundOpacity;
  89104. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89105. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89106. this._groundMaterial.primaryLevel = 1;
  89107. this._groundMaterial.primaryColor = this._options.groundColor;
  89108. this._groundMaterial.secondaryLevel = 0;
  89109. this._groundMaterial.tertiaryLevel = 0;
  89110. this._groundMaterial.useRGBColor = false;
  89111. this._groundMaterial.enableNoise = true;
  89112. if (this._ground) {
  89113. this._ground.material = this._groundMaterial;
  89114. }
  89115. };
  89116. /**
  89117. * Setup the ground diffuse texture according to the specified options.
  89118. */
  89119. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89120. if (!this._groundMaterial) {
  89121. return;
  89122. }
  89123. if (this._groundTexture) {
  89124. return;
  89125. }
  89126. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89127. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89128. return;
  89129. }
  89130. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89131. diffuseTexture.gammaSpace = false;
  89132. diffuseTexture.hasAlpha = true;
  89133. this._groundMaterial.diffuseTexture = diffuseTexture;
  89134. };
  89135. /**
  89136. * Setup the ground mirror texture according to the specified options.
  89137. */
  89138. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89139. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89140. if (!this._groundMirror) {
  89141. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89142. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89143. this._groundMirror.anisotropicFilteringLevel = 1;
  89144. this._groundMirror.wrapU = wrapping;
  89145. this._groundMirror.wrapV = wrapping;
  89146. this._groundMirror.gammaSpace = false;
  89147. if (this._groundMirror.renderList) {
  89148. for (var i = 0; i < this._scene.meshes.length; i++) {
  89149. var mesh = this._scene.meshes[i];
  89150. if (mesh !== this._ground &&
  89151. mesh !== this._skybox &&
  89152. mesh !== this._rootMesh) {
  89153. this._groundMirror.renderList.push(mesh);
  89154. }
  89155. }
  89156. }
  89157. }
  89158. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89159. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89160. };
  89161. /**
  89162. * Setup the ground to receive the mirror texture.
  89163. */
  89164. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89165. if (this._groundMaterial) {
  89166. this._groundMaterial.reflectionTexture = this._groundMirror;
  89167. this._groundMaterial.reflectionFresnel = true;
  89168. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89169. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89170. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89171. }
  89172. };
  89173. /**
  89174. * Setup the skybox according to the specified options.
  89175. */
  89176. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89177. var _this = this;
  89178. if (!this._skybox) {
  89179. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89180. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89181. }
  89182. this._skybox.parent = this._rootMesh;
  89183. };
  89184. /**
  89185. * Setup the skybox material according to the specified options.
  89186. */
  89187. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89188. if (!this._skybox) {
  89189. return;
  89190. }
  89191. if (!this._skyboxMaterial) {
  89192. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89193. }
  89194. this._skyboxMaterial.useRGBColor = false;
  89195. this._skyboxMaterial.primaryLevel = 1;
  89196. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89197. this._skyboxMaterial.secondaryLevel = 0;
  89198. this._skyboxMaterial.tertiaryLevel = 0;
  89199. this._skyboxMaterial.enableNoise = true;
  89200. this._skybox.material = this._skyboxMaterial;
  89201. };
  89202. /**
  89203. * Setup the skybox reflection texture according to the specified options.
  89204. */
  89205. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89206. if (!this._skyboxMaterial) {
  89207. return;
  89208. }
  89209. if (this._skyboxTexture) {
  89210. return;
  89211. }
  89212. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89213. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89214. return;
  89215. }
  89216. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89217. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89218. this._skyboxTexture.gammaSpace = false;
  89219. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89220. };
  89221. /**
  89222. * Dispose all the elements created by the Helper.
  89223. */
  89224. EnvironmentHelper.prototype.dispose = function () {
  89225. if (this._groundMaterial) {
  89226. this._groundMaterial.dispose(true, true);
  89227. }
  89228. if (this._skyboxMaterial) {
  89229. this._skyboxMaterial.dispose(true, true);
  89230. }
  89231. this._rootMesh.dispose(false);
  89232. };
  89233. /**
  89234. * Default ground texture URL.
  89235. */
  89236. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89237. /**
  89238. * Default skybox texture URL.
  89239. */
  89240. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89241. /**
  89242. * Default environment texture URL.
  89243. */
  89244. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89245. return EnvironmentHelper;
  89246. }());
  89247. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89248. })(BABYLON || (BABYLON = {}));
  89249. //# sourceMappingURL=babylon.environmentHelper.js.map
  89250. 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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\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\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#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  89251. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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","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};"};
  89252. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89253. var BABYLON;
  89254. (function (BABYLON) {
  89255. var GridMaterialDefines = /** @class */ (function (_super) {
  89256. __extends(GridMaterialDefines, _super);
  89257. function GridMaterialDefines() {
  89258. var _this = _super.call(this) || this;
  89259. _this.TRANSPARENT = false;
  89260. _this.FOG = false;
  89261. _this.PREMULTIPLYALPHA = false;
  89262. _this.rebuild();
  89263. return _this;
  89264. }
  89265. return GridMaterialDefines;
  89266. }(BABYLON.MaterialDefines));
  89267. /**
  89268. * The grid materials allows you to wrap any shape with a grid.
  89269. * Colors are customizable.
  89270. */
  89271. var GridMaterial = /** @class */ (function (_super) {
  89272. __extends(GridMaterial, _super);
  89273. /**
  89274. * constructor
  89275. * @param name The name given to the material in order to identify it afterwards.
  89276. * @param scene The scene the material is used in.
  89277. */
  89278. function GridMaterial(name, scene) {
  89279. var _this = _super.call(this, name, scene) || this;
  89280. /**
  89281. * Main color of the grid (e.g. between lines)
  89282. */
  89283. _this.mainColor = BABYLON.Color3.Black();
  89284. /**
  89285. * Color of the grid lines.
  89286. */
  89287. _this.lineColor = BABYLON.Color3.Teal();
  89288. /**
  89289. * The scale of the grid compared to unit.
  89290. */
  89291. _this.gridRatio = 1.0;
  89292. /**
  89293. * Allows setting an offset for the grid lines.
  89294. */
  89295. _this.gridOffset = BABYLON.Vector3.Zero();
  89296. /**
  89297. * The frequency of thicker lines.
  89298. */
  89299. _this.majorUnitFrequency = 10;
  89300. /**
  89301. * The visibility of minor units in the grid.
  89302. */
  89303. _this.minorUnitVisibility = 0.33;
  89304. /**
  89305. * The grid opacity outside of the lines.
  89306. */
  89307. _this.opacity = 1.0;
  89308. /**
  89309. * Determine RBG output is premultiplied by alpha value.
  89310. */
  89311. _this.preMultiplyAlpha = false;
  89312. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89313. return _this;
  89314. }
  89315. /**
  89316. * Returns wehter or not the grid requires alpha blending.
  89317. */
  89318. GridMaterial.prototype.needAlphaBlending = function () {
  89319. return this.opacity < 1.0;
  89320. };
  89321. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89322. return this.needAlphaBlending();
  89323. };
  89324. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89325. if (this.isFrozen) {
  89326. if (this._wasPreviouslyReady && subMesh.effect) {
  89327. return true;
  89328. }
  89329. }
  89330. if (!subMesh._materialDefines) {
  89331. subMesh._materialDefines = new GridMaterialDefines();
  89332. }
  89333. var defines = subMesh._materialDefines;
  89334. var scene = this.getScene();
  89335. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89336. if (this._renderId === scene.getRenderId()) {
  89337. return true;
  89338. }
  89339. }
  89340. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89341. defines.TRANSPARENT = !defines.TRANSPARENT;
  89342. defines.markAsUnprocessed();
  89343. }
  89344. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89345. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89346. defines.markAsUnprocessed();
  89347. }
  89348. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89349. // Get correct effect
  89350. if (defines.isDirty) {
  89351. defines.markAsProcessed();
  89352. scene.resetCachedMaterial();
  89353. // Attributes
  89354. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89355. // Defines
  89356. var join = defines.toString();
  89357. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89358. }
  89359. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89360. return false;
  89361. }
  89362. this._renderId = scene.getRenderId();
  89363. this._wasPreviouslyReady = true;
  89364. return true;
  89365. };
  89366. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89367. var scene = this.getScene();
  89368. var defines = subMesh._materialDefines;
  89369. if (!defines) {
  89370. return;
  89371. }
  89372. var effect = subMesh.effect;
  89373. if (!effect) {
  89374. return;
  89375. }
  89376. this._activeEffect = effect;
  89377. // Matrices
  89378. this.bindOnlyWorldMatrix(world);
  89379. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89380. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89381. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89382. // Uniforms
  89383. if (this._mustRebind(scene, effect)) {
  89384. this._activeEffect.setColor3("mainColor", this.mainColor);
  89385. this._activeEffect.setColor3("lineColor", this.lineColor);
  89386. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89387. this._gridControl.x = this.gridRatio;
  89388. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89389. this._gridControl.z = this.minorUnitVisibility;
  89390. this._gridControl.w = this.opacity;
  89391. this._activeEffect.setVector4("gridControl", this._gridControl);
  89392. }
  89393. // Fog
  89394. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89395. this._afterBind(mesh, this._activeEffect);
  89396. };
  89397. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89398. _super.prototype.dispose.call(this, forceDisposeEffect);
  89399. };
  89400. GridMaterial.prototype.clone = function (name) {
  89401. var _this = this;
  89402. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89403. };
  89404. GridMaterial.prototype.serialize = function () {
  89405. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89406. serializationObject.customType = "BABYLON.GridMaterial";
  89407. return serializationObject;
  89408. };
  89409. GridMaterial.prototype.getClassName = function () {
  89410. return "GridMaterial";
  89411. };
  89412. GridMaterial.Parse = function (source, scene, rootUrl) {
  89413. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89414. };
  89415. __decorate([
  89416. BABYLON.serializeAsColor3()
  89417. ], GridMaterial.prototype, "mainColor", void 0);
  89418. __decorate([
  89419. BABYLON.serializeAsColor3()
  89420. ], GridMaterial.prototype, "lineColor", void 0);
  89421. __decorate([
  89422. BABYLON.serialize()
  89423. ], GridMaterial.prototype, "gridRatio", void 0);
  89424. __decorate([
  89425. BABYLON.serializeAsColor3()
  89426. ], GridMaterial.prototype, "gridOffset", void 0);
  89427. __decorate([
  89428. BABYLON.serialize()
  89429. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89430. __decorate([
  89431. BABYLON.serialize()
  89432. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89433. __decorate([
  89434. BABYLON.serialize()
  89435. ], GridMaterial.prototype, "opacity", void 0);
  89436. __decorate([
  89437. BABYLON.serialize()
  89438. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89439. return GridMaterial;
  89440. }(BABYLON.PushMaterial));
  89441. BABYLON.GridMaterial = GridMaterial;
  89442. })(BABYLON || (BABYLON = {}));
  89443. //# sourceMappingURL=babylon.gridmaterial.js.map
  89444. 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}";
  89445. 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}";
  89446. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89447. var BABYLON;
  89448. (function (BABYLON) {
  89449. var GLTFLoaderCoordinateSystemMode;
  89450. (function (GLTFLoaderCoordinateSystemMode) {
  89451. /**
  89452. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89453. */
  89454. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89455. /**
  89456. * Sets the useRightHandedSystem flag on the scene.
  89457. */
  89458. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89459. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89460. var GLTFLoaderAnimationStartMode;
  89461. (function (GLTFLoaderAnimationStartMode) {
  89462. /**
  89463. * No animation will start.
  89464. */
  89465. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89466. /**
  89467. * The first animation will start.
  89468. */
  89469. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89470. /**
  89471. * All animations will start.
  89472. */
  89473. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89474. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89475. var GLTFLoaderState;
  89476. (function (GLTFLoaderState) {
  89477. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89478. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89479. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89480. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89481. var GLTFFileLoader = /** @class */ (function () {
  89482. function GLTFFileLoader() {
  89483. // #region Common options
  89484. /**
  89485. * Raised when the asset has been parsed.
  89486. * The data.json property stores the glTF JSON.
  89487. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89488. */
  89489. this.onParsedObservable = new BABYLON.Observable();
  89490. // #endregion
  89491. // #region V2 options
  89492. /**
  89493. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89494. */
  89495. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89496. /**
  89497. * The animation start mode (NONE, FIRST, ALL).
  89498. */
  89499. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89500. /**
  89501. * Set to true to compile materials before raising the success callback.
  89502. */
  89503. this.compileMaterials = false;
  89504. /**
  89505. * Set to true to also compile materials with clip planes.
  89506. */
  89507. this.useClipPlane = false;
  89508. /**
  89509. * Set to true to compile shadow generators before raising the success callback.
  89510. */
  89511. this.compileShadowGenerators = false;
  89512. /**
  89513. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89514. */
  89515. this.onMeshLoadedObservable = new BABYLON.Observable();
  89516. /**
  89517. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89518. */
  89519. this.onTextureLoadedObservable = new BABYLON.Observable();
  89520. /**
  89521. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89522. */
  89523. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89524. /**
  89525. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89526. * For assets with LODs, raised when all of the LODs are complete.
  89527. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89528. */
  89529. this.onCompleteObservable = new BABYLON.Observable();
  89530. /**
  89531. * Raised when the loader is disposed.
  89532. */
  89533. this.onDisposeObservable = new BABYLON.Observable();
  89534. /**
  89535. * Raised after a loader extension is created.
  89536. * Set additional options for a loader extension in this event.
  89537. */
  89538. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89539. // #endregion
  89540. this._loader = null;
  89541. this.name = "gltf";
  89542. this.extensions = {
  89543. ".gltf": { isBinary: false },
  89544. ".glb": { isBinary: true }
  89545. };
  89546. }
  89547. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89548. set: function (callback) {
  89549. if (this._onParsedObserver) {
  89550. this.onParsedObservable.remove(this._onParsedObserver);
  89551. }
  89552. this._onParsedObserver = this.onParsedObservable.add(callback);
  89553. },
  89554. enumerable: true,
  89555. configurable: true
  89556. });
  89557. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89558. set: function (callback) {
  89559. if (this._onMeshLoadedObserver) {
  89560. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89561. }
  89562. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89563. },
  89564. enumerable: true,
  89565. configurable: true
  89566. });
  89567. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89568. set: function (callback) {
  89569. if (this._onTextureLoadedObserver) {
  89570. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89571. }
  89572. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89573. },
  89574. enumerable: true,
  89575. configurable: true
  89576. });
  89577. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89578. set: function (callback) {
  89579. if (this._onMaterialLoadedObserver) {
  89580. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89581. }
  89582. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89583. },
  89584. enumerable: true,
  89585. configurable: true
  89586. });
  89587. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89588. set: function (callback) {
  89589. if (this._onCompleteObserver) {
  89590. this.onCompleteObservable.remove(this._onCompleteObserver);
  89591. }
  89592. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89593. },
  89594. enumerable: true,
  89595. configurable: true
  89596. });
  89597. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89598. set: function (callback) {
  89599. if (this._onDisposeObserver) {
  89600. this.onDisposeObservable.remove(this._onDisposeObserver);
  89601. }
  89602. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89603. },
  89604. enumerable: true,
  89605. configurable: true
  89606. });
  89607. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89608. set: function (callback) {
  89609. if (this._onExtensionLoadedObserver) {
  89610. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89611. }
  89612. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89613. },
  89614. enumerable: true,
  89615. configurable: true
  89616. });
  89617. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89618. /**
  89619. * The loader state or null if not active.
  89620. */
  89621. get: function () {
  89622. return this._loader ? this._loader.state : null;
  89623. },
  89624. enumerable: true,
  89625. configurable: true
  89626. });
  89627. /**
  89628. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89629. */
  89630. GLTFFileLoader.prototype.dispose = function () {
  89631. if (this._loader) {
  89632. this._loader.dispose();
  89633. this._loader = null;
  89634. }
  89635. this.onMeshLoadedObservable.clear();
  89636. this.onTextureLoadedObservable.clear();
  89637. this.onMaterialLoadedObservable.clear();
  89638. this.onDisposeObservable.notifyObservers(this);
  89639. this.onDisposeObservable.clear();
  89640. };
  89641. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89642. var _this = this;
  89643. return Promise.resolve().then(function () {
  89644. var loaderData = _this._parse(data);
  89645. _this._loader = _this._getLoader(loaderData);
  89646. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89647. });
  89648. };
  89649. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89650. var _this = this;
  89651. return Promise.resolve().then(function () {
  89652. var loaderData = _this._parse(data);
  89653. _this._loader = _this._getLoader(loaderData);
  89654. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89655. });
  89656. };
  89657. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89658. var _this = this;
  89659. return Promise.resolve().then(function () {
  89660. var loaderData = _this._parse(data);
  89661. _this._loader = _this._getLoader(loaderData);
  89662. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89663. var container = new BABYLON.AssetContainer(scene);
  89664. Array.prototype.push.apply(container.meshes, result.meshes);
  89665. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89666. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89667. container.removeAllFromScene();
  89668. return container;
  89669. });
  89670. });
  89671. };
  89672. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  89673. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  89674. };
  89675. GLTFFileLoader.prototype.createPlugin = function () {
  89676. return new GLTFFileLoader();
  89677. };
  89678. GLTFFileLoader.prototype._parse = function (data) {
  89679. var parsedData;
  89680. if (data instanceof ArrayBuffer) {
  89681. parsedData = GLTFFileLoader._parseBinary(data);
  89682. }
  89683. else {
  89684. parsedData = {
  89685. json: JSON.parse(data),
  89686. bin: null
  89687. };
  89688. }
  89689. this.onParsedObservable.notifyObservers(parsedData);
  89690. this.onParsedObservable.clear();
  89691. return parsedData;
  89692. };
  89693. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  89694. var _this = this;
  89695. var loaderVersion = { major: 2, minor: 0 };
  89696. var asset = loaderData.json.asset || {};
  89697. var version = GLTFFileLoader._parseVersion(asset.version);
  89698. if (!version) {
  89699. throw new Error("Invalid version: " + asset.version);
  89700. }
  89701. if (asset.minVersion !== undefined) {
  89702. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  89703. if (!minVersion) {
  89704. throw new Error("Invalid minimum version: " + asset.minVersion);
  89705. }
  89706. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  89707. throw new Error("Incompatible minimum version: " + asset.minVersion);
  89708. }
  89709. }
  89710. var createLoaders = {
  89711. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  89712. 2: GLTFFileLoader.CreateGLTFLoaderV2
  89713. };
  89714. var createLoader = createLoaders[version.major];
  89715. if (!createLoader) {
  89716. throw new Error("Unsupported version: " + asset.version);
  89717. }
  89718. var loader = createLoader();
  89719. loader.coordinateSystemMode = this.coordinateSystemMode;
  89720. loader.animationStartMode = this.animationStartMode;
  89721. loader.compileMaterials = this.compileMaterials;
  89722. loader.useClipPlane = this.useClipPlane;
  89723. loader.compileShadowGenerators = this.compileShadowGenerators;
  89724. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  89725. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  89726. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  89727. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  89728. loader.onCompleteObservable.add(function () {
  89729. _this.onMeshLoadedObservable.clear();
  89730. _this.onTextureLoadedObservable.clear();
  89731. _this.onMaterialLoadedObservable.clear();
  89732. _this.onCompleteObservable.notifyObservers(_this);
  89733. _this.onCompleteObservable.clear();
  89734. });
  89735. return loader;
  89736. };
  89737. GLTFFileLoader._parseBinary = function (data) {
  89738. var Binary = {
  89739. Magic: 0x46546C67
  89740. };
  89741. var binaryReader = new BinaryReader(data);
  89742. var magic = binaryReader.readUint32();
  89743. if (magic !== Binary.Magic) {
  89744. throw new Error("Unexpected magic: " + magic);
  89745. }
  89746. var version = binaryReader.readUint32();
  89747. switch (version) {
  89748. case 1: return GLTFFileLoader._parseV1(binaryReader);
  89749. case 2: return GLTFFileLoader._parseV2(binaryReader);
  89750. }
  89751. throw new Error("Unsupported version: " + version);
  89752. };
  89753. GLTFFileLoader._parseV1 = function (binaryReader) {
  89754. var ContentFormat = {
  89755. JSON: 0
  89756. };
  89757. var length = binaryReader.readUint32();
  89758. if (length != binaryReader.getLength()) {
  89759. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89760. }
  89761. var contentLength = binaryReader.readUint32();
  89762. var contentFormat = binaryReader.readUint32();
  89763. var content;
  89764. switch (contentFormat) {
  89765. case ContentFormat.JSON: {
  89766. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  89767. break;
  89768. }
  89769. default: {
  89770. throw new Error("Unexpected content format: " + contentFormat);
  89771. }
  89772. }
  89773. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  89774. var body = binaryReader.readUint8Array(bytesRemaining);
  89775. return {
  89776. json: content,
  89777. bin: body
  89778. };
  89779. };
  89780. GLTFFileLoader._parseV2 = function (binaryReader) {
  89781. var ChunkFormat = {
  89782. JSON: 0x4E4F534A,
  89783. BIN: 0x004E4942
  89784. };
  89785. var length = binaryReader.readUint32();
  89786. if (length !== binaryReader.getLength()) {
  89787. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89788. }
  89789. // JSON chunk
  89790. var chunkLength = binaryReader.readUint32();
  89791. var chunkFormat = binaryReader.readUint32();
  89792. if (chunkFormat !== ChunkFormat.JSON) {
  89793. throw new Error("First chunk format is not JSON");
  89794. }
  89795. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  89796. // Look for BIN chunk
  89797. var bin = null;
  89798. while (binaryReader.getPosition() < binaryReader.getLength()) {
  89799. var chunkLength_1 = binaryReader.readUint32();
  89800. var chunkFormat_1 = binaryReader.readUint32();
  89801. switch (chunkFormat_1) {
  89802. case ChunkFormat.JSON: {
  89803. throw new Error("Unexpected JSON chunk");
  89804. }
  89805. case ChunkFormat.BIN: {
  89806. bin = binaryReader.readUint8Array(chunkLength_1);
  89807. break;
  89808. }
  89809. default: {
  89810. // ignore unrecognized chunkFormat
  89811. binaryReader.skipBytes(chunkLength_1);
  89812. break;
  89813. }
  89814. }
  89815. }
  89816. return {
  89817. json: json,
  89818. bin: bin
  89819. };
  89820. };
  89821. GLTFFileLoader._parseVersion = function (version) {
  89822. if (version === "1.0" || version === "1.0.1") {
  89823. return {
  89824. major: 1,
  89825. minor: 0
  89826. };
  89827. }
  89828. var match = (version + "").match(/^(\d+)\.(\d+)/);
  89829. if (!match) {
  89830. return null;
  89831. }
  89832. return {
  89833. major: parseInt(match[1]),
  89834. minor: parseInt(match[2])
  89835. };
  89836. };
  89837. GLTFFileLoader._compareVersion = function (a, b) {
  89838. if (a.major > b.major)
  89839. return 1;
  89840. if (a.major < b.major)
  89841. return -1;
  89842. if (a.minor > b.minor)
  89843. return 1;
  89844. if (a.minor < b.minor)
  89845. return -1;
  89846. return 0;
  89847. };
  89848. GLTFFileLoader._decodeBufferToText = function (buffer) {
  89849. var result = "";
  89850. var length = buffer.byteLength;
  89851. for (var i = 0; i < length; i++) {
  89852. result += String.fromCharCode(buffer[i]);
  89853. }
  89854. return result;
  89855. };
  89856. // #endregion
  89857. // #region V1 options
  89858. GLTFFileLoader.IncrementalLoading = true;
  89859. GLTFFileLoader.HomogeneousCoordinates = false;
  89860. return GLTFFileLoader;
  89861. }());
  89862. BABYLON.GLTFFileLoader = GLTFFileLoader;
  89863. var BinaryReader = /** @class */ (function () {
  89864. function BinaryReader(arrayBuffer) {
  89865. this._arrayBuffer = arrayBuffer;
  89866. this._dataView = new DataView(arrayBuffer);
  89867. this._byteOffset = 0;
  89868. }
  89869. BinaryReader.prototype.getPosition = function () {
  89870. return this._byteOffset;
  89871. };
  89872. BinaryReader.prototype.getLength = function () {
  89873. return this._arrayBuffer.byteLength;
  89874. };
  89875. BinaryReader.prototype.readUint32 = function () {
  89876. var value = this._dataView.getUint32(this._byteOffset, true);
  89877. this._byteOffset += 4;
  89878. return value;
  89879. };
  89880. BinaryReader.prototype.readUint8Array = function (length) {
  89881. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  89882. this._byteOffset += length;
  89883. return value;
  89884. };
  89885. BinaryReader.prototype.skipBytes = function (length) {
  89886. this._byteOffset += length;
  89887. };
  89888. return BinaryReader;
  89889. }());
  89890. if (BABYLON.SceneLoader) {
  89891. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  89892. }
  89893. })(BABYLON || (BABYLON = {}));
  89894. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  89895. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89896. var BABYLON;
  89897. (function (BABYLON) {
  89898. var GLTF1;
  89899. (function (GLTF1) {
  89900. /**
  89901. * Enums
  89902. */
  89903. var EComponentType;
  89904. (function (EComponentType) {
  89905. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89906. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89907. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89908. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89909. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89910. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  89911. var EShaderType;
  89912. (function (EShaderType) {
  89913. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  89914. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  89915. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  89916. var EParameterType;
  89917. (function (EParameterType) {
  89918. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  89919. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89920. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  89921. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89922. EParameterType[EParameterType["INT"] = 5124] = "INT";
  89923. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  89924. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  89925. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  89926. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  89927. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  89928. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  89929. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  89930. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  89931. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  89932. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  89933. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  89934. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  89935. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  89936. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  89937. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  89938. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  89939. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  89940. var ETextureWrapMode;
  89941. (function (ETextureWrapMode) {
  89942. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  89943. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  89944. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  89945. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  89946. var ETextureFilterType;
  89947. (function (ETextureFilterType) {
  89948. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  89949. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  89950. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  89951. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  89952. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  89953. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  89954. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  89955. var ETextureFormat;
  89956. (function (ETextureFormat) {
  89957. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  89958. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  89959. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  89960. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  89961. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  89962. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  89963. var ECullingType;
  89964. (function (ECullingType) {
  89965. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  89966. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  89967. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  89968. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  89969. var EBlendingFunction;
  89970. (function (EBlendingFunction) {
  89971. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  89972. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  89973. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  89974. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  89975. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  89976. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  89977. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  89978. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  89979. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  89980. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  89981. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  89982. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  89983. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  89984. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  89985. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  89986. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  89987. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89988. })(BABYLON || (BABYLON = {}));
  89989. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  89990. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89991. var BABYLON;
  89992. (function (BABYLON) {
  89993. var GLTF1;
  89994. (function (GLTF1) {
  89995. /**
  89996. * Tokenizer. Used for shaders compatibility
  89997. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  89998. */
  89999. var ETokenType;
  90000. (function (ETokenType) {
  90001. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90002. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90003. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90004. })(ETokenType || (ETokenType = {}));
  90005. var Tokenizer = /** @class */ (function () {
  90006. function Tokenizer(toParse) {
  90007. this._pos = 0;
  90008. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90009. this._toParse = toParse;
  90010. this._maxPos = toParse.length;
  90011. }
  90012. Tokenizer.prototype.getNextToken = function () {
  90013. if (this.isEnd())
  90014. return ETokenType.END_OF_INPUT;
  90015. this.currentString = this.read();
  90016. this.currentToken = ETokenType.UNKNOWN;
  90017. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90018. this.currentToken = ETokenType.IDENTIFIER;
  90019. this.currentIdentifier = this.currentString;
  90020. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90021. this.currentIdentifier += this.currentString;
  90022. this.forward();
  90023. }
  90024. }
  90025. return this.currentToken;
  90026. };
  90027. Tokenizer.prototype.peek = function () {
  90028. return this._toParse[this._pos];
  90029. };
  90030. Tokenizer.prototype.read = function () {
  90031. return this._toParse[this._pos++];
  90032. };
  90033. Tokenizer.prototype.forward = function () {
  90034. this._pos++;
  90035. };
  90036. Tokenizer.prototype.isEnd = function () {
  90037. return this._pos >= this._maxPos;
  90038. };
  90039. return Tokenizer;
  90040. }());
  90041. /**
  90042. * Values
  90043. */
  90044. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90045. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90046. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90047. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90048. /**
  90049. * Parse
  90050. */
  90051. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90052. for (var buf in parsedBuffers) {
  90053. var parsedBuffer = parsedBuffers[buf];
  90054. gltfRuntime.buffers[buf] = parsedBuffer;
  90055. gltfRuntime.buffersCount++;
  90056. }
  90057. };
  90058. var parseShaders = function (parsedShaders, gltfRuntime) {
  90059. for (var sha in parsedShaders) {
  90060. var parsedShader = parsedShaders[sha];
  90061. gltfRuntime.shaders[sha] = parsedShader;
  90062. gltfRuntime.shaderscount++;
  90063. }
  90064. };
  90065. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90066. for (var object in parsedObjects) {
  90067. var parsedObject = parsedObjects[object];
  90068. gltfRuntime[runtimeProperty][object] = parsedObject;
  90069. }
  90070. };
  90071. /**
  90072. * Utils
  90073. */
  90074. var normalizeUVs = function (buffer) {
  90075. if (!buffer) {
  90076. return;
  90077. }
  90078. for (var i = 0; i < buffer.length / 2; i++) {
  90079. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90080. }
  90081. };
  90082. var getAttribute = function (attributeParameter) {
  90083. if (attributeParameter.semantic === "NORMAL") {
  90084. return "normal";
  90085. }
  90086. else if (attributeParameter.semantic === "POSITION") {
  90087. return "position";
  90088. }
  90089. else if (attributeParameter.semantic === "JOINT") {
  90090. return "matricesIndices";
  90091. }
  90092. else if (attributeParameter.semantic === "WEIGHT") {
  90093. return "matricesWeights";
  90094. }
  90095. else if (attributeParameter.semantic === "COLOR") {
  90096. return "color";
  90097. }
  90098. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90099. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90100. return "uv" + (channel === 0 ? "" : channel + 1);
  90101. }
  90102. return null;
  90103. };
  90104. /**
  90105. * Loads and creates animations
  90106. */
  90107. var loadAnimations = function (gltfRuntime) {
  90108. for (var anim in gltfRuntime.animations) {
  90109. var animation = gltfRuntime.animations[anim];
  90110. if (!animation.channels || !animation.samplers) {
  90111. continue;
  90112. }
  90113. var lastAnimation = null;
  90114. for (var i = 0; i < animation.channels.length; i++) {
  90115. // Get parameters and load buffers
  90116. var channel = animation.channels[i];
  90117. var sampler = animation.samplers[channel.sampler];
  90118. if (!sampler) {
  90119. continue;
  90120. }
  90121. var inputData = null;
  90122. var outputData = null;
  90123. if (animation.parameters) {
  90124. inputData = animation.parameters[sampler.input];
  90125. outputData = animation.parameters[sampler.output];
  90126. }
  90127. else {
  90128. inputData = sampler.input;
  90129. outputData = sampler.output;
  90130. }
  90131. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90132. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90133. var targetID = channel.target.id;
  90134. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90135. if (targetNode === null) {
  90136. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90137. }
  90138. if (targetNode === null) {
  90139. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90140. continue;
  90141. }
  90142. var isBone = targetNode instanceof BABYLON.Bone;
  90143. // Get target path (position, rotation or scaling)
  90144. var targetPath = channel.target.path;
  90145. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90146. if (targetPathIndex !== -1) {
  90147. targetPath = babylonAnimationPaths[targetPathIndex];
  90148. }
  90149. // Determine animation type
  90150. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90151. if (!isBone) {
  90152. if (targetPath === "rotationQuaternion") {
  90153. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90154. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90155. }
  90156. else {
  90157. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90158. }
  90159. }
  90160. // Create animation and key frames
  90161. var babylonAnimation = null;
  90162. var keys = [];
  90163. var arrayOffset = 0;
  90164. var modifyKey = false;
  90165. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90166. babylonAnimation = lastAnimation;
  90167. modifyKey = true;
  90168. }
  90169. if (!modifyKey) {
  90170. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90171. }
  90172. // For each frame
  90173. for (var j = 0; j < bufferInput.length; j++) {
  90174. var value = null;
  90175. if (targetPath === "rotationQuaternion") {
  90176. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90177. arrayOffset += 4;
  90178. }
  90179. else {
  90180. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90181. arrayOffset += 3;
  90182. }
  90183. if (isBone) {
  90184. var bone = targetNode;
  90185. var translation = BABYLON.Vector3.Zero();
  90186. var rotationQuaternion = new BABYLON.Quaternion();
  90187. var scaling = BABYLON.Vector3.Zero();
  90188. // Warning on decompose
  90189. var mat = bone.getBaseMatrix();
  90190. if (modifyKey && lastAnimation) {
  90191. mat = lastAnimation.getKeys()[j].value;
  90192. }
  90193. mat.decompose(scaling, rotationQuaternion, translation);
  90194. if (targetPath === "position") {
  90195. translation = value;
  90196. }
  90197. else if (targetPath === "rotationQuaternion") {
  90198. rotationQuaternion = value;
  90199. }
  90200. else {
  90201. scaling = value;
  90202. }
  90203. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90204. }
  90205. if (!modifyKey) {
  90206. keys.push({
  90207. frame: bufferInput[j],
  90208. value: value
  90209. });
  90210. }
  90211. else if (lastAnimation) {
  90212. lastAnimation.getKeys()[j].value = value;
  90213. }
  90214. }
  90215. // Finish
  90216. if (!modifyKey && babylonAnimation) {
  90217. babylonAnimation.setKeys(keys);
  90218. targetNode.animations.push(babylonAnimation);
  90219. }
  90220. lastAnimation = babylonAnimation;
  90221. gltfRuntime.scene.stopAnimation(targetNode);
  90222. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90223. }
  90224. }
  90225. };
  90226. /**
  90227. * Returns the bones transformation matrix
  90228. */
  90229. var configureBoneTransformation = function (node) {
  90230. var mat = null;
  90231. if (node.translation || node.rotation || node.scale) {
  90232. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90233. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90234. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90235. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90236. }
  90237. else {
  90238. mat = BABYLON.Matrix.FromArray(node.matrix);
  90239. }
  90240. return mat;
  90241. };
  90242. /**
  90243. * Returns the parent bone
  90244. */
  90245. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90246. // Try to find
  90247. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90248. if (newSkeleton.bones[i].name === jointName) {
  90249. return newSkeleton.bones[i];
  90250. }
  90251. }
  90252. // Not found, search in gltf nodes
  90253. var nodes = gltfRuntime.nodes;
  90254. for (var nde in nodes) {
  90255. var node = nodes[nde];
  90256. if (!node.jointName) {
  90257. continue;
  90258. }
  90259. var children = node.children;
  90260. for (var i = 0; i < children.length; i++) {
  90261. var child = gltfRuntime.nodes[children[i]];
  90262. if (!child.jointName) {
  90263. continue;
  90264. }
  90265. if (child.jointName === jointName) {
  90266. var mat = configureBoneTransformation(node);
  90267. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90268. bone.id = nde;
  90269. return bone;
  90270. }
  90271. }
  90272. }
  90273. return null;
  90274. };
  90275. /**
  90276. * Returns the appropriate root node
  90277. */
  90278. var getNodeToRoot = function (nodesToRoot, id) {
  90279. for (var i = 0; i < nodesToRoot.length; i++) {
  90280. var nodeToRoot = nodesToRoot[i];
  90281. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90282. var child = nodeToRoot.node.children[j];
  90283. if (child === id) {
  90284. return nodeToRoot.bone;
  90285. }
  90286. }
  90287. }
  90288. return null;
  90289. };
  90290. /**
  90291. * Returns the node with the joint name
  90292. */
  90293. var getJointNode = function (gltfRuntime, jointName) {
  90294. var nodes = gltfRuntime.nodes;
  90295. var node = nodes[jointName];
  90296. if (node) {
  90297. return {
  90298. node: node,
  90299. id: jointName
  90300. };
  90301. }
  90302. for (var nde in nodes) {
  90303. node = nodes[nde];
  90304. if (node.jointName === jointName) {
  90305. return {
  90306. node: node,
  90307. id: nde
  90308. };
  90309. }
  90310. }
  90311. return null;
  90312. };
  90313. /**
  90314. * Checks if a nodes is in joints
  90315. */
  90316. var nodeIsInJoints = function (skins, id) {
  90317. for (var i = 0; i < skins.jointNames.length; i++) {
  90318. if (skins.jointNames[i] === id) {
  90319. return true;
  90320. }
  90321. }
  90322. return false;
  90323. };
  90324. /**
  90325. * Fills the nodes to root for bones and builds hierarchy
  90326. */
  90327. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90328. // Creates nodes for root
  90329. for (var nde in gltfRuntime.nodes) {
  90330. var node = gltfRuntime.nodes[nde];
  90331. var id = nde;
  90332. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90333. continue;
  90334. }
  90335. // Create node to root bone
  90336. var mat = configureBoneTransformation(node);
  90337. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90338. bone.id = id;
  90339. nodesToRoot.push({ bone: bone, node: node, id: id });
  90340. }
  90341. // Parenting
  90342. for (var i = 0; i < nodesToRoot.length; i++) {
  90343. var nodeToRoot = nodesToRoot[i];
  90344. var children = nodeToRoot.node.children;
  90345. for (var j = 0; j < children.length; j++) {
  90346. var child = null;
  90347. for (var k = 0; k < nodesToRoot.length; k++) {
  90348. if (nodesToRoot[k].id === children[j]) {
  90349. child = nodesToRoot[k];
  90350. break;
  90351. }
  90352. }
  90353. if (child) {
  90354. child.bone._parent = nodeToRoot.bone;
  90355. nodeToRoot.bone.children.push(child.bone);
  90356. }
  90357. }
  90358. }
  90359. };
  90360. /**
  90361. * Imports a skeleton
  90362. */
  90363. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90364. if (!newSkeleton) {
  90365. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90366. }
  90367. if (!skins.babylonSkeleton) {
  90368. return newSkeleton;
  90369. }
  90370. // Find the root bones
  90371. var nodesToRoot = [];
  90372. var nodesToRootToAdd = [];
  90373. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90374. newSkeleton.bones = [];
  90375. // Joints
  90376. for (var i = 0; i < skins.jointNames.length; i++) {
  90377. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90378. if (!jointNode) {
  90379. continue;
  90380. }
  90381. var node = jointNode.node;
  90382. if (!node) {
  90383. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90384. continue;
  90385. }
  90386. var id = jointNode.id;
  90387. // Optimize, if the bone already exists...
  90388. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90389. if (existingBone) {
  90390. newSkeleton.bones.push(existingBone);
  90391. continue;
  90392. }
  90393. // Search for parent bone
  90394. var foundBone = false;
  90395. var parentBone = null;
  90396. for (var j = 0; j < i; j++) {
  90397. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90398. if (!jointNode_1) {
  90399. continue;
  90400. }
  90401. var joint = jointNode_1.node;
  90402. if (!joint) {
  90403. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90404. continue;
  90405. }
  90406. var children = joint.children;
  90407. if (!children) {
  90408. continue;
  90409. }
  90410. foundBone = false;
  90411. for (var k = 0; k < children.length; k++) {
  90412. if (children[k] === id) {
  90413. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90414. foundBone = true;
  90415. break;
  90416. }
  90417. }
  90418. if (foundBone) {
  90419. break;
  90420. }
  90421. }
  90422. // Create bone
  90423. var mat = configureBoneTransformation(node);
  90424. if (!parentBone && nodesToRoot.length > 0) {
  90425. parentBone = getNodeToRoot(nodesToRoot, id);
  90426. if (parentBone) {
  90427. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90428. nodesToRootToAdd.push(parentBone);
  90429. }
  90430. }
  90431. }
  90432. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90433. bone.id = id;
  90434. }
  90435. // Polish
  90436. var bones = newSkeleton.bones;
  90437. newSkeleton.bones = [];
  90438. for (var i = 0; i < skins.jointNames.length; i++) {
  90439. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90440. if (!jointNode) {
  90441. continue;
  90442. }
  90443. for (var j = 0; j < bones.length; j++) {
  90444. if (bones[j].id === jointNode.id) {
  90445. newSkeleton.bones.push(bones[j]);
  90446. break;
  90447. }
  90448. }
  90449. }
  90450. newSkeleton.prepare();
  90451. // Finish
  90452. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90453. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90454. }
  90455. return newSkeleton;
  90456. };
  90457. /**
  90458. * Imports a mesh and its geometries
  90459. */
  90460. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90461. if (!newMesh) {
  90462. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90463. newMesh.id = id;
  90464. }
  90465. if (!node.babylonNode) {
  90466. return newMesh;
  90467. }
  90468. var subMaterials = [];
  90469. var vertexData = null;
  90470. var verticesStarts = new Array();
  90471. var verticesCounts = new Array();
  90472. var indexStarts = new Array();
  90473. var indexCounts = new Array();
  90474. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90475. var meshID = meshes[meshIndex];
  90476. var mesh = gltfRuntime.meshes[meshID];
  90477. if (!mesh) {
  90478. continue;
  90479. }
  90480. // Positions, normals and UVs
  90481. for (var i = 0; i < mesh.primitives.length; i++) {
  90482. // Temporary vertex data
  90483. var tempVertexData = new BABYLON.VertexData();
  90484. var primitive = mesh.primitives[i];
  90485. if (primitive.mode !== 4) {
  90486. // continue;
  90487. }
  90488. var attributes = primitive.attributes;
  90489. var accessor = null;
  90490. var buffer = null;
  90491. // Set positions, normal and uvs
  90492. for (var semantic in attributes) {
  90493. // Link accessor and buffer view
  90494. accessor = gltfRuntime.accessors[attributes[semantic]];
  90495. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90496. if (semantic === "NORMAL") {
  90497. tempVertexData.normals = new Float32Array(buffer.length);
  90498. tempVertexData.normals.set(buffer);
  90499. }
  90500. else if (semantic === "POSITION") {
  90501. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90502. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90503. for (var j = 0; j < buffer.length; j += 4) {
  90504. tempVertexData.positions[j] = buffer[j];
  90505. tempVertexData.positions[j + 1] = buffer[j + 1];
  90506. tempVertexData.positions[j + 2] = buffer[j + 2];
  90507. }
  90508. }
  90509. else {
  90510. tempVertexData.positions = new Float32Array(buffer.length);
  90511. tempVertexData.positions.set(buffer);
  90512. }
  90513. verticesCounts.push(tempVertexData.positions.length);
  90514. }
  90515. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90516. var channel = Number(semantic.split("_")[1]);
  90517. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90518. var uvs = new Float32Array(buffer.length);
  90519. uvs.set(buffer);
  90520. normalizeUVs(uvs);
  90521. tempVertexData.set(uvs, uvKind);
  90522. }
  90523. else if (semantic === "JOINT") {
  90524. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90525. tempVertexData.matricesIndices.set(buffer);
  90526. }
  90527. else if (semantic === "WEIGHT") {
  90528. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90529. tempVertexData.matricesWeights.set(buffer);
  90530. }
  90531. else if (semantic === "COLOR") {
  90532. tempVertexData.colors = new Float32Array(buffer.length);
  90533. tempVertexData.colors.set(buffer);
  90534. }
  90535. }
  90536. // Indices
  90537. accessor = gltfRuntime.accessors[primitive.indices];
  90538. if (accessor) {
  90539. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90540. tempVertexData.indices = new Int32Array(buffer.length);
  90541. tempVertexData.indices.set(buffer);
  90542. indexCounts.push(tempVertexData.indices.length);
  90543. }
  90544. else {
  90545. // Set indices on the fly
  90546. var indices = [];
  90547. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90548. indices.push(j);
  90549. }
  90550. tempVertexData.indices = new Int32Array(indices);
  90551. indexCounts.push(tempVertexData.indices.length);
  90552. }
  90553. if (!vertexData) {
  90554. vertexData = tempVertexData;
  90555. }
  90556. else {
  90557. vertexData.merge(tempVertexData);
  90558. }
  90559. // Sub material
  90560. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90561. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90562. // Update vertices start and index start
  90563. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90564. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90565. }
  90566. }
  90567. var material;
  90568. if (subMaterials.length > 1) {
  90569. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90570. material.subMaterials = subMaterials;
  90571. }
  90572. else {
  90573. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90574. }
  90575. if (subMaterials.length === 1) {
  90576. material = subMaterials[0];
  90577. }
  90578. if (!newMesh.material) {
  90579. newMesh.material = material;
  90580. }
  90581. // Apply geometry
  90582. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90583. newMesh.computeWorldMatrix(true);
  90584. // Apply submeshes
  90585. newMesh.subMeshes = [];
  90586. var index = 0;
  90587. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90588. var meshID = meshes[meshIndex];
  90589. var mesh = gltfRuntime.meshes[meshID];
  90590. if (!mesh) {
  90591. continue;
  90592. }
  90593. for (var i = 0; i < mesh.primitives.length; i++) {
  90594. if (mesh.primitives[i].mode !== 4) {
  90595. //continue;
  90596. }
  90597. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90598. index++;
  90599. }
  90600. }
  90601. // Finish
  90602. return newMesh;
  90603. };
  90604. /**
  90605. * Configure node transformation from position, rotation and scaling
  90606. */
  90607. var configureNode = function (newNode, position, rotation, scaling) {
  90608. if (newNode.position) {
  90609. newNode.position = position;
  90610. }
  90611. if (newNode.rotationQuaternion || newNode.rotation) {
  90612. newNode.rotationQuaternion = rotation;
  90613. }
  90614. if (newNode.scaling) {
  90615. newNode.scaling = scaling;
  90616. }
  90617. };
  90618. /**
  90619. * Configures node from transformation matrix
  90620. */
  90621. var configureNodeFromMatrix = function (newNode, node, parent) {
  90622. if (node.matrix) {
  90623. var position = new BABYLON.Vector3(0, 0, 0);
  90624. var rotation = new BABYLON.Quaternion();
  90625. var scaling = new BABYLON.Vector3(0, 0, 0);
  90626. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90627. mat.decompose(scaling, rotation, position);
  90628. configureNode(newNode, position, rotation, scaling);
  90629. }
  90630. else if (node.translation && node.rotation && node.scale) {
  90631. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90632. }
  90633. newNode.computeWorldMatrix(true);
  90634. };
  90635. /**
  90636. * Imports a node
  90637. */
  90638. var importNode = function (gltfRuntime, node, id, parent) {
  90639. var lastNode = null;
  90640. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90641. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90642. return null;
  90643. }
  90644. }
  90645. // Meshes
  90646. if (node.skin) {
  90647. if (node.meshes) {
  90648. var skin = gltfRuntime.skins[node.skin];
  90649. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90650. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90651. if (newMesh.skeleton === null) {
  90652. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90653. if (!skin.babylonSkeleton) {
  90654. skin.babylonSkeleton = newMesh.skeleton;
  90655. }
  90656. }
  90657. lastNode = newMesh;
  90658. }
  90659. }
  90660. else if (node.meshes) {
  90661. /**
  90662. * Improve meshes property
  90663. */
  90664. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90665. lastNode = newMesh;
  90666. }
  90667. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90668. var light = gltfRuntime.lights[node.light];
  90669. if (light) {
  90670. if (light.type === "ambient") {
  90671. var ambienLight = light[light.type];
  90672. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90673. hemiLight.name = node.name || "";
  90674. if (ambienLight.color) {
  90675. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  90676. }
  90677. lastNode = hemiLight;
  90678. }
  90679. else if (light.type === "directional") {
  90680. var directionalLight = light[light.type];
  90681. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90682. dirLight.name = node.name || "";
  90683. if (directionalLight.color) {
  90684. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  90685. }
  90686. lastNode = dirLight;
  90687. }
  90688. else if (light.type === "point") {
  90689. var pointLight = light[light.type];
  90690. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90691. ptLight.name = node.name || "";
  90692. if (pointLight.color) {
  90693. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  90694. }
  90695. lastNode = ptLight;
  90696. }
  90697. else if (light.type === "spot") {
  90698. var spotLight = light[light.type];
  90699. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  90700. spLight.name = node.name || "";
  90701. if (spotLight.color) {
  90702. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  90703. }
  90704. if (spotLight.fallOfAngle) {
  90705. spLight.angle = spotLight.fallOfAngle;
  90706. }
  90707. if (spotLight.fallOffExponent) {
  90708. spLight.exponent = spotLight.fallOffExponent;
  90709. }
  90710. lastNode = spLight;
  90711. }
  90712. }
  90713. }
  90714. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90715. var camera = gltfRuntime.cameras[node.camera];
  90716. if (camera) {
  90717. if (camera.type === "orthographic") {
  90718. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90719. orthoCamera.name = node.name || "";
  90720. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  90721. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90722. lastNode = orthoCamera;
  90723. }
  90724. else if (camera.type === "perspective") {
  90725. var perspectiveCamera = camera[camera.type];
  90726. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90727. persCamera.name = node.name || "";
  90728. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90729. if (!perspectiveCamera.aspectRatio) {
  90730. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  90731. }
  90732. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  90733. persCamera.maxZ = perspectiveCamera.zfar;
  90734. persCamera.minZ = perspectiveCamera.znear;
  90735. }
  90736. lastNode = persCamera;
  90737. }
  90738. }
  90739. }
  90740. // Empty node
  90741. if (!node.jointName) {
  90742. if (node.babylonNode) {
  90743. return node.babylonNode;
  90744. }
  90745. else if (lastNode === null) {
  90746. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90747. node.babylonNode = dummy;
  90748. lastNode = dummy;
  90749. }
  90750. }
  90751. if (lastNode !== null) {
  90752. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  90753. configureNodeFromMatrix(lastNode, node, parent);
  90754. }
  90755. else {
  90756. var translation = node.translation || [0, 0, 0];
  90757. var rotation = node.rotation || [0, 0, 0, 1];
  90758. var scale = node.scale || [1, 1, 1];
  90759. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  90760. }
  90761. lastNode.updateCache(true);
  90762. node.babylonNode = lastNode;
  90763. }
  90764. return lastNode;
  90765. };
  90766. /**
  90767. * Traverses nodes and creates them
  90768. */
  90769. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  90770. if (meshIncluded === void 0) { meshIncluded = false; }
  90771. var node = gltfRuntime.nodes[id];
  90772. var newNode = null;
  90773. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  90774. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  90775. meshIncluded = true;
  90776. }
  90777. else {
  90778. meshIncluded = false;
  90779. }
  90780. }
  90781. else {
  90782. meshIncluded = true;
  90783. }
  90784. if (!node.jointName && meshIncluded) {
  90785. newNode = importNode(gltfRuntime, node, id, parent);
  90786. if (newNode !== null) {
  90787. newNode.id = id;
  90788. newNode.parent = parent;
  90789. }
  90790. }
  90791. if (node.children) {
  90792. for (var i = 0; i < node.children.length; i++) {
  90793. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  90794. }
  90795. }
  90796. };
  90797. /**
  90798. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  90799. */
  90800. var postLoad = function (gltfRuntime) {
  90801. // Nodes
  90802. var currentScene = gltfRuntime.currentScene;
  90803. if (currentScene) {
  90804. for (var i = 0; i < currentScene.nodes.length; i++) {
  90805. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90806. }
  90807. }
  90808. else {
  90809. for (var thing in gltfRuntime.scenes) {
  90810. currentScene = gltfRuntime.scenes[thing];
  90811. for (var i = 0; i < currentScene.nodes.length; i++) {
  90812. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90813. }
  90814. }
  90815. }
  90816. // Set animations
  90817. loadAnimations(gltfRuntime);
  90818. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  90819. var skeleton = gltfRuntime.scene.skeletons[i];
  90820. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  90821. }
  90822. };
  90823. /**
  90824. * onBind shaderrs callback to set uniforms and matrices
  90825. */
  90826. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  90827. var materialValues = material.values || technique.parameters;
  90828. for (var unif in unTreatedUniforms) {
  90829. var uniform = unTreatedUniforms[unif];
  90830. var type = uniform.type;
  90831. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  90832. if (uniform.semantic && !uniform.source && !uniform.node) {
  90833. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  90834. }
  90835. else if (uniform.semantic && (uniform.source || uniform.node)) {
  90836. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  90837. if (source === null) {
  90838. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  90839. }
  90840. if (source === null) {
  90841. continue;
  90842. }
  90843. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  90844. }
  90845. }
  90846. else {
  90847. var value = materialValues[technique.uniforms[unif]];
  90848. if (!value) {
  90849. continue;
  90850. }
  90851. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90852. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  90853. if (texture === null || texture === undefined) {
  90854. continue;
  90855. }
  90856. shaderMaterial.getEffect().setTexture(unif, texture);
  90857. }
  90858. else {
  90859. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  90860. }
  90861. }
  90862. }
  90863. onSuccess(shaderMaterial);
  90864. };
  90865. /**
  90866. * Prepare uniforms to send the only one time
  90867. * Loads the appropriate textures
  90868. */
  90869. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  90870. var materialValues = material.values || technique.parameters;
  90871. var techniqueUniforms = technique.uniforms;
  90872. /**
  90873. * Prepare values here (not matrices)
  90874. */
  90875. for (var unif in unTreatedUniforms) {
  90876. var uniform = unTreatedUniforms[unif];
  90877. var type = uniform.type;
  90878. var value = materialValues[techniqueUniforms[unif]];
  90879. if (value === undefined) {
  90880. // In case the value is the same for all materials
  90881. value = uniform.value;
  90882. }
  90883. if (!value) {
  90884. continue;
  90885. }
  90886. var onLoadTexture = function (uniformName) {
  90887. return function (texture) {
  90888. if (uniform.value && uniformName) {
  90889. // Static uniform
  90890. shaderMaterial.setTexture(uniformName, texture);
  90891. delete unTreatedUniforms[uniformName];
  90892. }
  90893. };
  90894. };
  90895. // Texture (sampler2D)
  90896. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90897. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  90898. }
  90899. else {
  90900. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  90901. // Static uniform
  90902. delete unTreatedUniforms[unif];
  90903. }
  90904. }
  90905. }
  90906. };
  90907. /**
  90908. * Shader compilation failed
  90909. */
  90910. var onShaderCompileError = function (program, shaderMaterial, onError) {
  90911. return function (effect, error) {
  90912. shaderMaterial.dispose(true);
  90913. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  90914. };
  90915. };
  90916. /**
  90917. * Shader compilation success
  90918. */
  90919. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  90920. return function (_) {
  90921. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  90922. shaderMaterial.onBind = function (mesh) {
  90923. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  90924. };
  90925. };
  90926. };
  90927. /**
  90928. * Returns the appropriate uniform if already handled by babylon
  90929. */
  90930. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  90931. for (var unif in technique.uniforms) {
  90932. var uniform = technique.uniforms[unif];
  90933. var uniformParameter = technique.parameters[uniform];
  90934. if (tokenizer.currentIdentifier === unif) {
  90935. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  90936. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90937. if (transformIndex !== -1) {
  90938. delete unTreatedUniforms[unif];
  90939. return babylonTransforms[transformIndex];
  90940. }
  90941. }
  90942. }
  90943. }
  90944. return tokenizer.currentIdentifier;
  90945. };
  90946. /**
  90947. * All shaders loaded. Create materials one by one
  90948. */
  90949. var importMaterials = function (gltfRuntime) {
  90950. // Create materials
  90951. for (var mat in gltfRuntime.materials) {
  90952. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  90953. }
  90954. };
  90955. /**
  90956. * Implementation of the base glTF spec
  90957. */
  90958. var GLTFLoaderBase = /** @class */ (function () {
  90959. function GLTFLoaderBase() {
  90960. }
  90961. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  90962. var gltfRuntime = {
  90963. extensions: {},
  90964. accessors: {},
  90965. buffers: {},
  90966. bufferViews: {},
  90967. meshes: {},
  90968. lights: {},
  90969. cameras: {},
  90970. nodes: {},
  90971. images: {},
  90972. textures: {},
  90973. shaders: {},
  90974. programs: {},
  90975. samplers: {},
  90976. techniques: {},
  90977. materials: {},
  90978. animations: {},
  90979. skins: {},
  90980. extensionsUsed: [],
  90981. scenes: {},
  90982. buffersCount: 0,
  90983. shaderscount: 0,
  90984. scene: scene,
  90985. rootUrl: rootUrl,
  90986. loadedBufferCount: 0,
  90987. loadedBufferViews: {},
  90988. loadedShaderCount: 0,
  90989. importOnlyMeshes: false,
  90990. dummyNodes: []
  90991. };
  90992. // Parse
  90993. if (parsedData.extensions) {
  90994. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  90995. }
  90996. if (parsedData.extensionsUsed) {
  90997. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  90998. }
  90999. if (parsedData.buffers) {
  91000. parseBuffers(parsedData.buffers, gltfRuntime);
  91001. }
  91002. if (parsedData.bufferViews) {
  91003. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91004. }
  91005. if (parsedData.accessors) {
  91006. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91007. }
  91008. if (parsedData.meshes) {
  91009. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91010. }
  91011. if (parsedData.lights) {
  91012. parseObject(parsedData.lights, "lights", gltfRuntime);
  91013. }
  91014. if (parsedData.cameras) {
  91015. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91016. }
  91017. if (parsedData.nodes) {
  91018. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91019. }
  91020. if (parsedData.images) {
  91021. parseObject(parsedData.images, "images", gltfRuntime);
  91022. }
  91023. if (parsedData.textures) {
  91024. parseObject(parsedData.textures, "textures", gltfRuntime);
  91025. }
  91026. if (parsedData.shaders) {
  91027. parseShaders(parsedData.shaders, gltfRuntime);
  91028. }
  91029. if (parsedData.programs) {
  91030. parseObject(parsedData.programs, "programs", gltfRuntime);
  91031. }
  91032. if (parsedData.samplers) {
  91033. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91034. }
  91035. if (parsedData.techniques) {
  91036. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91037. }
  91038. if (parsedData.materials) {
  91039. parseObject(parsedData.materials, "materials", gltfRuntime);
  91040. }
  91041. if (parsedData.animations) {
  91042. parseObject(parsedData.animations, "animations", gltfRuntime);
  91043. }
  91044. if (parsedData.skins) {
  91045. parseObject(parsedData.skins, "skins", gltfRuntime);
  91046. }
  91047. if (parsedData.scenes) {
  91048. gltfRuntime.scenes = parsedData.scenes;
  91049. }
  91050. if (parsedData.scene && parsedData.scenes) {
  91051. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91052. }
  91053. return gltfRuntime;
  91054. };
  91055. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91056. var buffer = gltfRuntime.buffers[id];
  91057. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91058. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91059. }
  91060. else {
  91061. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91062. if (request) {
  91063. onError(request.status + " " + request.statusText);
  91064. }
  91065. });
  91066. }
  91067. };
  91068. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91069. var texture = gltfRuntime.textures[id];
  91070. if (!texture || !texture.source) {
  91071. onError("");
  91072. return;
  91073. }
  91074. if (texture.babylonTexture) {
  91075. onSuccess(null);
  91076. return;
  91077. }
  91078. var source = gltfRuntime.images[texture.source];
  91079. if (BABYLON.Tools.IsBase64(source.uri)) {
  91080. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91081. }
  91082. else {
  91083. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91084. if (request) {
  91085. onError(request.status + " " + request.statusText);
  91086. }
  91087. });
  91088. }
  91089. };
  91090. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91091. var texture = gltfRuntime.textures[id];
  91092. if (texture.babylonTexture) {
  91093. onSuccess(texture.babylonTexture);
  91094. return;
  91095. }
  91096. var sampler = gltfRuntime.samplers[texture.sampler];
  91097. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91098. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91099. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91100. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91101. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91102. var blob = new Blob([buffer]);
  91103. var blobURL = URL.createObjectURL(blob);
  91104. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91105. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91106. if (sampler.wrapS !== undefined) {
  91107. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91108. }
  91109. if (sampler.wrapT !== undefined) {
  91110. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91111. }
  91112. newTexture.name = id;
  91113. texture.babylonTexture = newTexture;
  91114. onSuccess(newTexture);
  91115. };
  91116. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91117. var shader = gltfRuntime.shaders[id];
  91118. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91119. var shaderString = atob(shader.uri.split(",")[1]);
  91120. onSuccess(shaderString);
  91121. }
  91122. else {
  91123. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91124. if (request) {
  91125. onError(request.status + " " + request.statusText);
  91126. }
  91127. });
  91128. }
  91129. };
  91130. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91131. var material = gltfRuntime.materials[id];
  91132. if (!material.technique) {
  91133. if (onError) {
  91134. onError("No technique found.");
  91135. }
  91136. return;
  91137. }
  91138. var technique = gltfRuntime.techniques[material.technique];
  91139. if (!technique) {
  91140. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91141. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91142. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91143. onSuccess(defaultMaterial);
  91144. return;
  91145. }
  91146. var program = gltfRuntime.programs[technique.program];
  91147. var states = technique.states;
  91148. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91149. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91150. var newVertexShader = "";
  91151. var newPixelShader = "";
  91152. var vertexTokenizer = new Tokenizer(vertexShader);
  91153. var pixelTokenizer = new Tokenizer(pixelShader);
  91154. var unTreatedUniforms = {};
  91155. var uniforms = [];
  91156. var attributes = [];
  91157. var samplers = [];
  91158. // Fill uniform, sampler2D and attributes
  91159. for (var unif in technique.uniforms) {
  91160. var uniform = technique.uniforms[unif];
  91161. var uniformParameter = technique.parameters[uniform];
  91162. unTreatedUniforms[unif] = uniformParameter;
  91163. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91164. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91165. if (transformIndex !== -1) {
  91166. uniforms.push(babylonTransforms[transformIndex]);
  91167. delete unTreatedUniforms[unif];
  91168. }
  91169. else {
  91170. uniforms.push(unif);
  91171. }
  91172. }
  91173. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91174. samplers.push(unif);
  91175. }
  91176. else {
  91177. uniforms.push(unif);
  91178. }
  91179. }
  91180. for (var attr in technique.attributes) {
  91181. var attribute = technique.attributes[attr];
  91182. var attributeParameter = technique.parameters[attribute];
  91183. if (attributeParameter.semantic) {
  91184. attributes.push(getAttribute(attributeParameter));
  91185. }
  91186. }
  91187. // Configure vertex shader
  91188. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91189. var tokenType = vertexTokenizer.currentToken;
  91190. if (tokenType !== ETokenType.IDENTIFIER) {
  91191. newVertexShader += vertexTokenizer.currentString;
  91192. continue;
  91193. }
  91194. var foundAttribute = false;
  91195. for (var attr in technique.attributes) {
  91196. var attribute = technique.attributes[attr];
  91197. var attributeParameter = technique.parameters[attribute];
  91198. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91199. newVertexShader += getAttribute(attributeParameter);
  91200. foundAttribute = true;
  91201. break;
  91202. }
  91203. }
  91204. if (foundAttribute) {
  91205. continue;
  91206. }
  91207. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91208. }
  91209. // Configure pixel shader
  91210. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91211. var tokenType = pixelTokenizer.currentToken;
  91212. if (tokenType !== ETokenType.IDENTIFIER) {
  91213. newPixelShader += pixelTokenizer.currentString;
  91214. continue;
  91215. }
  91216. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91217. }
  91218. // Create shader material
  91219. var shaderPath = {
  91220. vertex: program.vertexShader + id,
  91221. fragment: program.fragmentShader + id
  91222. };
  91223. var options = {
  91224. attributes: attributes,
  91225. uniforms: uniforms,
  91226. samplers: samplers,
  91227. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91228. };
  91229. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91230. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91231. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91232. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91233. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91234. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91235. if (states && states.functions) {
  91236. var functions = states.functions;
  91237. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91238. shaderMaterial.backFaceCulling = false;
  91239. }
  91240. var blendFunc = functions.blendFuncSeparate;
  91241. if (blendFunc) {
  91242. 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) {
  91243. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91244. }
  91245. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91246. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91247. }
  91248. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91249. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91250. }
  91251. 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) {
  91252. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91253. }
  91254. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91255. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91256. }
  91257. 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) {
  91258. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91259. }
  91260. }
  91261. }
  91262. };
  91263. return GLTFLoaderBase;
  91264. }());
  91265. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91266. /**
  91267. * glTF V1 Loader
  91268. */
  91269. var GLTFLoader = /** @class */ (function () {
  91270. function GLTFLoader() {
  91271. // #region Stubs for IGLTFLoader interface
  91272. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91273. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91274. this.compileMaterials = false;
  91275. this.useClipPlane = false;
  91276. this.compileShadowGenerators = false;
  91277. this.onDisposeObservable = new BABYLON.Observable();
  91278. this.onMeshLoadedObservable = new BABYLON.Observable();
  91279. this.onTextureLoadedObservable = new BABYLON.Observable();
  91280. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91281. this.onCompleteObservable = new BABYLON.Observable();
  91282. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91283. this.state = null;
  91284. }
  91285. GLTFLoader.RegisterExtension = function (extension) {
  91286. if (GLTFLoader.Extensions[extension.name]) {
  91287. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91288. return;
  91289. }
  91290. GLTFLoader.Extensions[extension.name] = extension;
  91291. };
  91292. GLTFLoader.prototype.dispose = function () { };
  91293. // #endregion
  91294. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91295. var _this = this;
  91296. scene.useRightHandedSystem = true;
  91297. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91298. gltfRuntime.importOnlyMeshes = true;
  91299. if (meshesNames === "") {
  91300. gltfRuntime.importMeshesNames = [];
  91301. }
  91302. else if (typeof meshesNames === "string") {
  91303. gltfRuntime.importMeshesNames = [meshesNames];
  91304. }
  91305. else if (meshesNames && !(meshesNames instanceof Array)) {
  91306. gltfRuntime.importMeshesNames = [meshesNames];
  91307. }
  91308. else {
  91309. gltfRuntime.importMeshesNames = [];
  91310. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91311. }
  91312. // Create nodes
  91313. _this._createNodes(gltfRuntime);
  91314. var meshes = new Array();
  91315. var skeletons = new Array();
  91316. // Fill arrays of meshes and skeletons
  91317. for (var nde in gltfRuntime.nodes) {
  91318. var node = gltfRuntime.nodes[nde];
  91319. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91320. meshes.push(node.babylonNode);
  91321. }
  91322. }
  91323. for (var skl in gltfRuntime.skins) {
  91324. var skin = gltfRuntime.skins[skl];
  91325. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91326. skeletons.push(skin.babylonSkeleton);
  91327. }
  91328. }
  91329. // Load buffers, shaders, materials, etc.
  91330. _this._loadBuffersAsync(gltfRuntime, function () {
  91331. _this._loadShadersAsync(gltfRuntime, function () {
  91332. importMaterials(gltfRuntime);
  91333. postLoad(gltfRuntime);
  91334. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91335. onSuccess(meshes, [], skeletons);
  91336. }
  91337. });
  91338. }, onProgress);
  91339. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91340. onSuccess(meshes, [], skeletons);
  91341. }
  91342. }, onError);
  91343. return true;
  91344. };
  91345. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91346. var _this = this;
  91347. return new Promise(function (resolve, reject) {
  91348. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91349. resolve({
  91350. meshes: meshes,
  91351. particleSystems: particleSystems,
  91352. skeletons: skeletons
  91353. });
  91354. }, onProgress, function (message) {
  91355. reject(new Error(message));
  91356. });
  91357. });
  91358. };
  91359. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91360. var _this = this;
  91361. scene.useRightHandedSystem = true;
  91362. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91363. // Load runtime extensios
  91364. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91365. // Create nodes
  91366. _this._createNodes(gltfRuntime);
  91367. // Load buffers, shaders, materials, etc.
  91368. _this._loadBuffersAsync(gltfRuntime, function () {
  91369. _this._loadShadersAsync(gltfRuntime, function () {
  91370. importMaterials(gltfRuntime);
  91371. postLoad(gltfRuntime);
  91372. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91373. onSuccess();
  91374. }
  91375. });
  91376. });
  91377. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91378. onSuccess();
  91379. }
  91380. }, onError);
  91381. }, onError);
  91382. };
  91383. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91384. var _this = this;
  91385. return new Promise(function (resolve, reject) {
  91386. _this._loadAsync(scene, data, rootUrl, function () {
  91387. resolve();
  91388. }, onProgress, function (message) {
  91389. reject(new Error(message));
  91390. });
  91391. });
  91392. };
  91393. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91394. var hasShaders = false;
  91395. var processShader = function (sha, shader) {
  91396. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91397. gltfRuntime.loadedShaderCount++;
  91398. if (shaderString) {
  91399. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91400. }
  91401. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91402. onload();
  91403. }
  91404. }, function () {
  91405. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91406. });
  91407. };
  91408. for (var sha in gltfRuntime.shaders) {
  91409. hasShaders = true;
  91410. var shader = gltfRuntime.shaders[sha];
  91411. if (shader) {
  91412. processShader.bind(this, sha, shader)();
  91413. }
  91414. else {
  91415. BABYLON.Tools.Error("No shader named: " + sha);
  91416. }
  91417. }
  91418. if (!hasShaders) {
  91419. onload();
  91420. }
  91421. };
  91422. ;
  91423. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91424. var hasBuffers = false;
  91425. var processBuffer = function (buf, buffer) {
  91426. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91427. gltfRuntime.loadedBufferCount++;
  91428. if (bufferView) {
  91429. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91430. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91431. }
  91432. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91433. }
  91434. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91435. onLoad();
  91436. }
  91437. }, function () {
  91438. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91439. });
  91440. };
  91441. for (var buf in gltfRuntime.buffers) {
  91442. hasBuffers = true;
  91443. var buffer = gltfRuntime.buffers[buf];
  91444. if (buffer) {
  91445. processBuffer.bind(this, buf, buffer)();
  91446. }
  91447. else {
  91448. BABYLON.Tools.Error("No buffer named: " + buf);
  91449. }
  91450. }
  91451. if (!hasBuffers) {
  91452. onLoad();
  91453. }
  91454. };
  91455. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91456. var currentScene = gltfRuntime.currentScene;
  91457. if (currentScene) {
  91458. // Only one scene even if multiple scenes are defined
  91459. for (var i = 0; i < currentScene.nodes.length; i++) {
  91460. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91461. }
  91462. }
  91463. else {
  91464. // Load all scenes
  91465. for (var thing in gltfRuntime.scenes) {
  91466. currentScene = gltfRuntime.scenes[thing];
  91467. for (var i = 0; i < currentScene.nodes.length; i++) {
  91468. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91469. }
  91470. }
  91471. }
  91472. };
  91473. GLTFLoader.Extensions = {};
  91474. return GLTFLoader;
  91475. }());
  91476. GLTF1.GLTFLoader = GLTFLoader;
  91477. ;
  91478. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91479. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91480. })(BABYLON || (BABYLON = {}));
  91481. //# sourceMappingURL=babylon.glTFLoader.js.map
  91482. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91483. var BABYLON;
  91484. (function (BABYLON) {
  91485. var GLTF1;
  91486. (function (GLTF1) {
  91487. /**
  91488. * Utils functions for GLTF
  91489. */
  91490. var GLTFUtils = /** @class */ (function () {
  91491. function GLTFUtils() {
  91492. }
  91493. /**
  91494. * Sets the given "parameter" matrix
  91495. * @param scene: the {BABYLON.Scene} object
  91496. * @param source: the source node where to pick the matrix
  91497. * @param parameter: the GLTF technique parameter
  91498. * @param uniformName: the name of the shader's uniform
  91499. * @param shaderMaterial: the shader material
  91500. */
  91501. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91502. var mat = null;
  91503. if (parameter.semantic === "MODEL") {
  91504. mat = source.getWorldMatrix();
  91505. }
  91506. else if (parameter.semantic === "PROJECTION") {
  91507. mat = scene.getProjectionMatrix();
  91508. }
  91509. else if (parameter.semantic === "VIEW") {
  91510. mat = scene.getViewMatrix();
  91511. }
  91512. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91513. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91514. }
  91515. else if (parameter.semantic === "MODELVIEW") {
  91516. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91517. }
  91518. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91519. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91520. }
  91521. else if (parameter.semantic === "MODELINVERSE") {
  91522. mat = source.getWorldMatrix().invert();
  91523. }
  91524. else if (parameter.semantic === "VIEWINVERSE") {
  91525. mat = scene.getViewMatrix().invert();
  91526. }
  91527. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91528. mat = scene.getProjectionMatrix().invert();
  91529. }
  91530. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91531. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91532. }
  91533. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91534. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91535. }
  91536. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91537. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91538. }
  91539. else {
  91540. debugger;
  91541. }
  91542. if (mat) {
  91543. switch (parameter.type) {
  91544. case GLTF1.EParameterType.FLOAT_MAT2:
  91545. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91546. break;
  91547. case GLTF1.EParameterType.FLOAT_MAT3:
  91548. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91549. break;
  91550. case GLTF1.EParameterType.FLOAT_MAT4:
  91551. shaderMaterial.setMatrix(uniformName, mat);
  91552. break;
  91553. default: break;
  91554. }
  91555. }
  91556. };
  91557. /**
  91558. * Sets the given "parameter" matrix
  91559. * @param shaderMaterial: the shader material
  91560. * @param uniform: the name of the shader's uniform
  91561. * @param value: the value of the uniform
  91562. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91563. */
  91564. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91565. switch (type) {
  91566. case GLTF1.EParameterType.FLOAT:
  91567. shaderMaterial.setFloat(uniform, value);
  91568. return true;
  91569. case GLTF1.EParameterType.FLOAT_VEC2:
  91570. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91571. return true;
  91572. case GLTF1.EParameterType.FLOAT_VEC3:
  91573. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91574. return true;
  91575. case GLTF1.EParameterType.FLOAT_VEC4:
  91576. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91577. return true;
  91578. default: return false;
  91579. }
  91580. };
  91581. /**
  91582. * Returns the wrap mode of the texture
  91583. * @param mode: the mode value
  91584. */
  91585. GLTFUtils.GetWrapMode = function (mode) {
  91586. switch (mode) {
  91587. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91588. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91589. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91590. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91591. }
  91592. };
  91593. /**
  91594. * Returns the byte stride giving an accessor
  91595. * @param accessor: the GLTF accessor objet
  91596. */
  91597. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91598. // Needs this function since "byteStride" isn't requiered in glTF format
  91599. var type = accessor.type;
  91600. switch (type) {
  91601. case "VEC2": return 2;
  91602. case "VEC3": return 3;
  91603. case "VEC4": return 4;
  91604. case "MAT2": return 4;
  91605. case "MAT3": return 9;
  91606. case "MAT4": return 16;
  91607. default: return 1;
  91608. }
  91609. };
  91610. /**
  91611. * Returns the texture filter mode giving a mode value
  91612. * @param mode: the filter mode value
  91613. */
  91614. GLTFUtils.GetTextureFilterMode = function (mode) {
  91615. switch (mode) {
  91616. case GLTF1.ETextureFilterType.LINEAR:
  91617. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91618. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91619. case GLTF1.ETextureFilterType.NEAREST:
  91620. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91621. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91622. }
  91623. };
  91624. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91625. var byteOffset = bufferView.byteOffset + byteOffset;
  91626. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91627. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91628. throw new Error("Buffer access is out of range");
  91629. }
  91630. var buffer = loadedBufferView.buffer;
  91631. byteOffset += loadedBufferView.byteOffset;
  91632. switch (componentType) {
  91633. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91634. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91635. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91636. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91637. default: return new Float32Array(buffer, byteOffset, byteLength);
  91638. }
  91639. };
  91640. /**
  91641. * Returns a buffer from its accessor
  91642. * @param gltfRuntime: the GLTF runtime
  91643. * @param accessor: the GLTF accessor
  91644. */
  91645. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91646. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91647. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91648. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91649. };
  91650. /**
  91651. * Decodes a buffer view into a string
  91652. * @param view: the buffer view
  91653. */
  91654. GLTFUtils.DecodeBufferToText = function (view) {
  91655. var result = "";
  91656. var length = view.byteLength;
  91657. for (var i = 0; i < length; ++i) {
  91658. result += String.fromCharCode(view[i]);
  91659. }
  91660. return result;
  91661. };
  91662. /**
  91663. * Returns the default material of gltf. Related to
  91664. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91665. * @param scene: the Babylon.js scene
  91666. */
  91667. GLTFUtils.GetDefaultMaterial = function (scene) {
  91668. if (!GLTFUtils._DefaultMaterial) {
  91669. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  91670. "precision highp float;",
  91671. "",
  91672. "uniform mat4 worldView;",
  91673. "uniform mat4 projection;",
  91674. "",
  91675. "attribute vec3 position;",
  91676. "",
  91677. "void main(void)",
  91678. "{",
  91679. " gl_Position = projection * worldView * vec4(position, 1.0);",
  91680. "}"
  91681. ].join("\n");
  91682. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  91683. "precision highp float;",
  91684. "",
  91685. "uniform vec4 u_emission;",
  91686. "",
  91687. "void main(void)",
  91688. "{",
  91689. " gl_FragColor = u_emission;",
  91690. "}"
  91691. ].join("\n");
  91692. var shaderPath = {
  91693. vertex: "GLTFDefaultMaterial",
  91694. fragment: "GLTFDefaultMaterial"
  91695. };
  91696. var options = {
  91697. attributes: ["position"],
  91698. uniforms: ["worldView", "projection", "u_emission"],
  91699. samplers: new Array(),
  91700. needAlphaBlending: false
  91701. };
  91702. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  91703. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  91704. }
  91705. return GLTFUtils._DefaultMaterial;
  91706. };
  91707. // The GLTF default material
  91708. GLTFUtils._DefaultMaterial = null;
  91709. return GLTFUtils;
  91710. }());
  91711. GLTF1.GLTFUtils = GLTFUtils;
  91712. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91713. })(BABYLON || (BABYLON = {}));
  91714. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91715. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91716. var BABYLON;
  91717. (function (BABYLON) {
  91718. var GLTF1;
  91719. (function (GLTF1) {
  91720. var GLTFLoaderExtension = /** @class */ (function () {
  91721. function GLTFLoaderExtension(name) {
  91722. this._name = name;
  91723. }
  91724. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  91725. get: function () {
  91726. return this._name;
  91727. },
  91728. enumerable: true,
  91729. configurable: true
  91730. });
  91731. /**
  91732. * Defines an override for loading the runtime
  91733. * Return true to stop further extensions from loading the runtime
  91734. */
  91735. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91736. return false;
  91737. };
  91738. /**
  91739. * Defines an onverride for creating gltf runtime
  91740. * Return true to stop further extensions from creating the runtime
  91741. */
  91742. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91743. return false;
  91744. };
  91745. /**
  91746. * Defines an override for loading buffers
  91747. * Return true to stop further extensions from loading this buffer
  91748. */
  91749. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91750. return false;
  91751. };
  91752. /**
  91753. * Defines an override for loading texture buffers
  91754. * Return true to stop further extensions from loading this texture data
  91755. */
  91756. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91757. return false;
  91758. };
  91759. /**
  91760. * Defines an override for creating textures
  91761. * Return true to stop further extensions from loading this texture
  91762. */
  91763. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91764. return false;
  91765. };
  91766. /**
  91767. * Defines an override for loading shader strings
  91768. * Return true to stop further extensions from loading this shader data
  91769. */
  91770. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91771. return false;
  91772. };
  91773. /**
  91774. * Defines an override for loading materials
  91775. * Return true to stop further extensions from loading this material
  91776. */
  91777. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91778. return false;
  91779. };
  91780. // ---------
  91781. // Utilities
  91782. // ---------
  91783. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91784. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91785. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  91786. }, function () {
  91787. setTimeout(function () {
  91788. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91789. });
  91790. });
  91791. };
  91792. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91793. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91794. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  91795. }, function () {
  91796. setTimeout(function () {
  91797. onSuccess();
  91798. });
  91799. });
  91800. };
  91801. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91802. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91803. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91804. }, function () {
  91805. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91806. });
  91807. };
  91808. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  91809. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  91810. };
  91811. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91812. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91813. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91814. }, function () {
  91815. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91816. });
  91817. };
  91818. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91819. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91820. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91821. }, function () {
  91822. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91823. });
  91824. };
  91825. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91826. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91827. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91828. }, function () {
  91829. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91830. });
  91831. };
  91832. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91833. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91834. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91835. }, function () {
  91836. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91837. });
  91838. };
  91839. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  91840. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  91841. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  91842. if (func(loaderExtension)) {
  91843. return;
  91844. }
  91845. }
  91846. defaultFunc();
  91847. };
  91848. return GLTFLoaderExtension;
  91849. }());
  91850. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  91851. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91852. })(BABYLON || (BABYLON = {}));
  91853. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91854. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91855. var BABYLON;
  91856. (function (BABYLON) {
  91857. var GLTF1;
  91858. (function (GLTF1) {
  91859. var BinaryExtensionBufferName = "binary_glTF";
  91860. ;
  91861. ;
  91862. var GLTFBinaryExtension = /** @class */ (function (_super) {
  91863. __extends(GLTFBinaryExtension, _super);
  91864. function GLTFBinaryExtension() {
  91865. return _super.call(this, "KHR_binary_glTF") || this;
  91866. }
  91867. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91868. var extensionsUsed = data.json.extensionsUsed;
  91869. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  91870. return false;
  91871. }
  91872. this._bin = data.bin;
  91873. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91874. return true;
  91875. };
  91876. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91877. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  91878. return false;
  91879. }
  91880. if (id !== BinaryExtensionBufferName) {
  91881. return false;
  91882. }
  91883. onSuccess(this._bin);
  91884. return true;
  91885. };
  91886. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91887. var texture = gltfRuntime.textures[id];
  91888. var source = gltfRuntime.images[texture.source];
  91889. if (!source.extensions || !(this.name in source.extensions)) {
  91890. return false;
  91891. }
  91892. var sourceExt = source.extensions[this.name];
  91893. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  91894. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91895. onSuccess(buffer);
  91896. return true;
  91897. };
  91898. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91899. var shader = gltfRuntime.shaders[id];
  91900. if (!shader.extensions || !(this.name in shader.extensions)) {
  91901. return false;
  91902. }
  91903. var binaryExtensionShader = shader.extensions[this.name];
  91904. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  91905. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91906. setTimeout(function () {
  91907. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  91908. onSuccess(shaderString);
  91909. });
  91910. return true;
  91911. };
  91912. return GLTFBinaryExtension;
  91913. }(GLTF1.GLTFLoaderExtension));
  91914. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  91915. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  91916. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91917. })(BABYLON || (BABYLON = {}));
  91918. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  91919. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91920. var BABYLON;
  91921. (function (BABYLON) {
  91922. var GLTF1;
  91923. (function (GLTF1) {
  91924. ;
  91925. ;
  91926. ;
  91927. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  91928. __extends(GLTFMaterialsCommonExtension, _super);
  91929. function GLTFMaterialsCommonExtension() {
  91930. return _super.call(this, "KHR_materials_common") || this;
  91931. }
  91932. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91933. if (!gltfRuntime.extensions)
  91934. return false;
  91935. var extension = gltfRuntime.extensions[this.name];
  91936. if (!extension)
  91937. return false;
  91938. // Create lights
  91939. var lights = extension.lights;
  91940. if (lights) {
  91941. for (var thing in lights) {
  91942. var light = lights[thing];
  91943. switch (light.type) {
  91944. case "ambient":
  91945. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  91946. var ambient = light.ambient;
  91947. if (ambient) {
  91948. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  91949. }
  91950. break;
  91951. case "point":
  91952. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  91953. var point = light.point;
  91954. if (point) {
  91955. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  91956. }
  91957. break;
  91958. case "directional":
  91959. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  91960. var directional = light.directional;
  91961. if (directional) {
  91962. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  91963. }
  91964. break;
  91965. case "spot":
  91966. var spot = light.spot;
  91967. if (spot) {
  91968. 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);
  91969. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  91970. }
  91971. break;
  91972. default:
  91973. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  91974. break;
  91975. }
  91976. }
  91977. }
  91978. return false;
  91979. };
  91980. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91981. var material = gltfRuntime.materials[id];
  91982. if (!material || !material.extensions)
  91983. return false;
  91984. var extension = material.extensions[this.name];
  91985. if (!extension)
  91986. return false;
  91987. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91988. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91989. if (extension.technique === "CONSTANT") {
  91990. standardMaterial.disableLighting = true;
  91991. }
  91992. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  91993. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  91994. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  91995. // Ambient
  91996. if (typeof extension.values.ambient === "string") {
  91997. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  91998. }
  91999. else {
  92000. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92001. }
  92002. // Diffuse
  92003. if (typeof extension.values.diffuse === "string") {
  92004. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92005. }
  92006. else {
  92007. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92008. }
  92009. // Emission
  92010. if (typeof extension.values.emission === "string") {
  92011. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92012. }
  92013. else {
  92014. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92015. }
  92016. // Specular
  92017. if (typeof extension.values.specular === "string") {
  92018. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92019. }
  92020. else {
  92021. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92022. }
  92023. return true;
  92024. };
  92025. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92026. // Create buffer from texture url
  92027. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92028. // Create texture from buffer
  92029. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92030. }, onError);
  92031. };
  92032. return GLTFMaterialsCommonExtension;
  92033. }(GLTF1.GLTFLoaderExtension));
  92034. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92035. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92036. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92037. })(BABYLON || (BABYLON = {}));
  92038. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92039. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92040. var BABYLON;
  92041. (function (BABYLON) {
  92042. var GLTF2;
  92043. (function (GLTF2) {
  92044. var ArrayItem = /** @class */ (function () {
  92045. function ArrayItem() {
  92046. }
  92047. ArrayItem.Assign = function (values) {
  92048. if (values) {
  92049. for (var index = 0; index < values.length; index++) {
  92050. values[index]._index = index;
  92051. }
  92052. }
  92053. };
  92054. return ArrayItem;
  92055. }());
  92056. GLTF2.ArrayItem = ArrayItem;
  92057. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92058. })(BABYLON || (BABYLON = {}));
  92059. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92060. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92061. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92062. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92063. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92064. var BABYLON;
  92065. (function (BABYLON) {
  92066. var GLTF2;
  92067. (function (GLTF2) {
  92068. var GLTFLoader = /** @class */ (function () {
  92069. function GLTFLoader() {
  92070. this._completePromises = new Array();
  92071. this._disposed = false;
  92072. this._state = null;
  92073. this._extensions = {};
  92074. this._defaultSampler = {};
  92075. this._requests = new Array();
  92076. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92077. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92078. this.compileMaterials = false;
  92079. this.useClipPlane = false;
  92080. this.compileShadowGenerators = false;
  92081. this.onDisposeObservable = new BABYLON.Observable();
  92082. this.onMeshLoadedObservable = new BABYLON.Observable();
  92083. this.onTextureLoadedObservable = new BABYLON.Observable();
  92084. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92085. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92086. this.onCompleteObservable = new BABYLON.Observable();
  92087. }
  92088. GLTFLoader._Register = function (name, factory) {
  92089. if (GLTFLoader._Factories[name]) {
  92090. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92091. return;
  92092. }
  92093. GLTFLoader._Factories[name] = factory;
  92094. // Keep the order of registration so that extensions registered first are called first.
  92095. GLTFLoader._Names.push(name);
  92096. };
  92097. Object.defineProperty(GLTFLoader.prototype, "state", {
  92098. get: function () {
  92099. return this._state;
  92100. },
  92101. enumerable: true,
  92102. configurable: true
  92103. });
  92104. GLTFLoader.prototype.dispose = function () {
  92105. if (this._disposed) {
  92106. return;
  92107. }
  92108. this._disposed = true;
  92109. this.onDisposeObservable.notifyObservers(this);
  92110. this.onDisposeObservable.clear();
  92111. this._clear();
  92112. };
  92113. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92114. var _this = this;
  92115. return Promise.resolve().then(function () {
  92116. var nodes = null;
  92117. if (meshesNames) {
  92118. var nodeMap_1 = {};
  92119. if (_this._gltf.nodes) {
  92120. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92121. var node = _a[_i];
  92122. if (node.name) {
  92123. nodeMap_1[node.name] = node;
  92124. }
  92125. }
  92126. }
  92127. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92128. nodes = names.map(function (name) {
  92129. var node = nodeMap_1[name];
  92130. if (!node) {
  92131. throw new Error("Failed to find node " + name);
  92132. }
  92133. return node;
  92134. });
  92135. }
  92136. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92137. return {
  92138. meshes: _this._getMeshes(),
  92139. particleSystems: [],
  92140. skeletons: _this._getSkeletons(),
  92141. };
  92142. });
  92143. });
  92144. };
  92145. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92146. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92147. };
  92148. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92149. var _this = this;
  92150. return Promise.resolve().then(function () {
  92151. _this._loadExtensions();
  92152. _this._babylonScene = scene;
  92153. _this._rootUrl = rootUrl;
  92154. _this._progressCallback = onProgress;
  92155. _this._state = BABYLON.GLTFLoaderState.Loading;
  92156. _this._loadData(data);
  92157. _this._checkExtensions();
  92158. var promises = new Array();
  92159. if (nodes) {
  92160. promises.push(_this._loadNodesAsync(nodes));
  92161. }
  92162. else {
  92163. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92164. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92165. }
  92166. if (_this.compileMaterials) {
  92167. promises.push(_this._compileMaterialsAsync());
  92168. }
  92169. if (_this.compileShadowGenerators) {
  92170. promises.push(_this._compileShadowGeneratorsAsync());
  92171. }
  92172. return Promise.all(promises).then(function () {
  92173. _this._state = BABYLON.GLTFLoaderState.Ready;
  92174. _this._startAnimations();
  92175. BABYLON.Tools.SetImmediate(function () {
  92176. if (!_this._disposed) {
  92177. Promise.all(_this._completePromises).then(function () {
  92178. _this._state = BABYLON.GLTFLoaderState.Complete;
  92179. _this.onCompleteObservable.notifyObservers(_this);
  92180. _this.onCompleteObservable.clear();
  92181. _this._clear();
  92182. }).catch(function (error) {
  92183. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92184. _this._clear();
  92185. });
  92186. }
  92187. });
  92188. });
  92189. }).catch(function (error) {
  92190. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92191. _this._clear();
  92192. throw error;
  92193. });
  92194. };
  92195. GLTFLoader.prototype._loadExtensions = function () {
  92196. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92197. var name_1 = _a[_i];
  92198. var extension = GLTFLoader._Factories[name_1](this);
  92199. this._extensions[name_1] = extension;
  92200. this.onExtensionLoadedObservable.notifyObservers(extension);
  92201. }
  92202. this.onExtensionLoadedObservable.clear();
  92203. };
  92204. GLTFLoader.prototype._loadData = function (data) {
  92205. this._gltf = data.json;
  92206. this._setupData();
  92207. if (data.bin) {
  92208. var buffers = this._gltf.buffers;
  92209. if (buffers && buffers[0] && !buffers[0].uri) {
  92210. var binaryBuffer = buffers[0];
  92211. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92212. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92213. }
  92214. binaryBuffer._data = Promise.resolve(data.bin);
  92215. }
  92216. else {
  92217. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92218. }
  92219. }
  92220. };
  92221. GLTFLoader.prototype._setupData = function () {
  92222. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92223. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92224. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92225. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92226. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92227. GLTF2.ArrayItem.Assign(this._gltf.images);
  92228. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92229. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92230. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92231. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92232. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92233. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92234. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92235. if (this._gltf.nodes) {
  92236. var nodeParents = {};
  92237. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92238. var node = _a[_i];
  92239. if (node.children) {
  92240. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92241. var index = _c[_b];
  92242. nodeParents[index] = node._index;
  92243. }
  92244. }
  92245. }
  92246. var rootNode = this._createRootNode();
  92247. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92248. var node = _e[_d];
  92249. var parentIndex = nodeParents[node._index];
  92250. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92251. }
  92252. }
  92253. };
  92254. GLTFLoader.prototype._checkExtensions = function () {
  92255. if (this._gltf.extensionsRequired) {
  92256. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92257. var name_2 = _a[_i];
  92258. var extension = this._extensions[name_2];
  92259. if (!extension || !extension.enabled) {
  92260. throw new Error("Require extension " + name_2 + " is not available");
  92261. }
  92262. }
  92263. }
  92264. };
  92265. GLTFLoader.prototype._createRootNode = function () {
  92266. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92267. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92268. switch (this.coordinateSystemMode) {
  92269. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92270. if (!this._babylonScene.useRightHandedSystem) {
  92271. rootNode.rotation = [0, 1, 0, 0];
  92272. rootNode.scale = [1, 1, -1];
  92273. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92274. }
  92275. break;
  92276. }
  92277. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92278. this._babylonScene.useRightHandedSystem = true;
  92279. break;
  92280. }
  92281. default: {
  92282. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92283. }
  92284. }
  92285. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92286. return rootNode;
  92287. };
  92288. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92289. var promises = new Array();
  92290. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92291. var node = nodes_1[_i];
  92292. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92293. }
  92294. promises.push(this._loadAnimationsAsync());
  92295. return Promise.all(promises).then(function () { });
  92296. };
  92297. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92298. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92299. if (promise) {
  92300. return promise;
  92301. }
  92302. var promises = new Array();
  92303. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92304. var index = _a[_i];
  92305. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92306. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92307. }
  92308. promises.push(this._loadAnimationsAsync());
  92309. return Promise.all(promises).then(function () { });
  92310. };
  92311. GLTFLoader.prototype._getMeshes = function () {
  92312. var meshes = new Array();
  92313. // Root mesh is always first.
  92314. meshes.push(this._rootBabylonMesh);
  92315. var nodes = this._gltf.nodes;
  92316. if (nodes) {
  92317. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92318. var node = nodes_2[_i];
  92319. if (node._babylonMesh) {
  92320. meshes.push(node._babylonMesh);
  92321. }
  92322. if (node._primitiveBabylonMeshes) {
  92323. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92324. var babylonMesh = _b[_a];
  92325. meshes.push(babylonMesh);
  92326. }
  92327. }
  92328. }
  92329. }
  92330. return meshes;
  92331. };
  92332. GLTFLoader.prototype._getSkeletons = function () {
  92333. var skeletons = new Array();
  92334. var skins = this._gltf.skins;
  92335. if (skins) {
  92336. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92337. var skin = skins_1[_i];
  92338. if (skin._babylonSkeleton) {
  92339. skeletons.push(skin._babylonSkeleton);
  92340. }
  92341. }
  92342. }
  92343. return skeletons;
  92344. };
  92345. GLTFLoader.prototype._startAnimations = function () {
  92346. var animations = this._gltf.animations;
  92347. if (!animations) {
  92348. return;
  92349. }
  92350. switch (this.animationStartMode) {
  92351. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92352. // do nothing
  92353. break;
  92354. }
  92355. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92356. var animation = animations[0];
  92357. animation._babylonAnimationGroup.start(true);
  92358. break;
  92359. }
  92360. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92361. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92362. var animation = animations_1[_i];
  92363. animation._babylonAnimationGroup.start(true);
  92364. }
  92365. break;
  92366. }
  92367. default: {
  92368. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92369. return;
  92370. }
  92371. }
  92372. };
  92373. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92374. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92375. if (promise) {
  92376. return promise;
  92377. }
  92378. if (node._babylonMesh) {
  92379. throw new Error(context + ": Invalid recursive node hierarchy");
  92380. }
  92381. var promises = new Array();
  92382. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92383. node._babylonMesh = babylonMesh;
  92384. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92385. node._babylonAnimationTargets.push(babylonMesh);
  92386. GLTFLoader._LoadTransform(node, babylonMesh);
  92387. if (node.mesh != undefined) {
  92388. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92389. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92390. }
  92391. if (node.children) {
  92392. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92393. var index = _a[_i];
  92394. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92395. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92396. }
  92397. }
  92398. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92399. return Promise.all(promises).then(function () { });
  92400. };
  92401. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92402. // TODO: instancing
  92403. var promises = new Array();
  92404. var primitives = mesh.primitives;
  92405. if (!primitives || primitives.length === 0) {
  92406. throw new Error(context + ": Primitives are missing");
  92407. }
  92408. GLTF2.ArrayItem.Assign(primitives);
  92409. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92410. var primitive = primitives_1[_i];
  92411. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92412. }
  92413. if (node.skin != undefined) {
  92414. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92415. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92416. }
  92417. return Promise.all(promises).then(function () {
  92418. if (node._primitiveBabylonMeshes) {
  92419. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92420. var primitiveBabylonMesh = _a[_i];
  92421. primitiveBabylonMesh._refreshBoundingInfo(true);
  92422. }
  92423. }
  92424. });
  92425. };
  92426. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92427. var _this = this;
  92428. var promises = new Array();
  92429. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92430. babylonMesh.setEnabled(false);
  92431. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92432. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92433. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92434. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92435. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92436. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92437. }));
  92438. if (primitive.material == undefined) {
  92439. babylonMesh.material = this._getDefaultMaterial();
  92440. }
  92441. else {
  92442. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92443. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  92444. }
  92445. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92446. return Promise.all(promises).then(function () {
  92447. babylonMesh.setEnabled(true);
  92448. });
  92449. };
  92450. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92451. var _this = this;
  92452. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92453. if (promise) {
  92454. return promise;
  92455. }
  92456. var attributes = primitive.attributes;
  92457. if (!attributes) {
  92458. throw new Error(context + ": Attributes are missing");
  92459. }
  92460. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92461. // TODO: handle other primitive modes
  92462. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92463. }
  92464. var promises = new Array();
  92465. var babylonVertexData = new BABYLON.VertexData();
  92466. if (primitive.indices == undefined) {
  92467. var positionAccessorIndex = attributes["POSITION"];
  92468. if (positionAccessorIndex != undefined) {
  92469. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92470. babylonVertexData.indices = new Uint32Array(accessor.count);
  92471. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92472. babylonVertexData.indices[i] = i;
  92473. }
  92474. }
  92475. }
  92476. else {
  92477. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92478. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92479. babylonVertexData.indices = data;
  92480. }));
  92481. }
  92482. var loadAttribute = function (attribute, kind) {
  92483. if (attributes[attribute] == undefined) {
  92484. return;
  92485. }
  92486. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92487. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92488. babylonMesh._delayInfo.push(kind);
  92489. }
  92490. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92491. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92492. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92493. if (attribute === "COLOR_0") {
  92494. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92495. babylonMesh.hasVertexAlpha = true;
  92496. if (accessor.type === "VEC3") {
  92497. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92498. }
  92499. }
  92500. babylonVertexData.set(attributeData, kind);
  92501. }));
  92502. };
  92503. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92504. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92505. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92506. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92507. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92508. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92509. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92510. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92511. return Promise.all(promises).then(function () {
  92512. return babylonVertexData;
  92513. });
  92514. };
  92515. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92516. if (!primitive.targets) {
  92517. return;
  92518. }
  92519. if (node._numMorphTargets == undefined) {
  92520. node._numMorphTargets = primitive.targets.length;
  92521. }
  92522. else if (primitive.targets.length !== node._numMorphTargets) {
  92523. throw new Error(context + ": Primitives do not have the same number of targets");
  92524. }
  92525. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92526. for (var index = 0; index < primitive.targets.length; index++) {
  92527. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92528. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92529. // TODO: tell the target whether it has positions, normals, tangents
  92530. }
  92531. };
  92532. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92533. if (!primitive.targets) {
  92534. return Promise.resolve();
  92535. }
  92536. var promises = new Array();
  92537. var morphTargetManager = babylonMesh.morphTargetManager;
  92538. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92539. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92540. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92541. }
  92542. return Promise.all(promises).then(function () { });
  92543. };
  92544. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92545. var _this = this;
  92546. var promises = new Array();
  92547. var loadAttribute = function (attribute, setData) {
  92548. if (attributes[attribute] == undefined) {
  92549. return;
  92550. }
  92551. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92552. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92553. setData(data);
  92554. }));
  92555. };
  92556. loadAttribute("POSITION", function (data) {
  92557. if (babylonVertexData.positions) {
  92558. for (var i = 0; i < data.length; i++) {
  92559. data[i] += babylonVertexData.positions[i];
  92560. }
  92561. babylonMorphTarget.setPositions(data);
  92562. }
  92563. });
  92564. loadAttribute("NORMAL", function (data) {
  92565. if (babylonVertexData.normals) {
  92566. for (var i = 0; i < data.length; i++) {
  92567. data[i] += babylonVertexData.normals[i];
  92568. }
  92569. babylonMorphTarget.setNormals(data);
  92570. }
  92571. });
  92572. loadAttribute("TANGENT", function (data) {
  92573. if (babylonVertexData.tangents) {
  92574. // Tangent data for morph targets is stored as xyz delta.
  92575. // The vertexData.tangent is stored as xyzw.
  92576. // So we need to skip every fourth vertexData.tangent.
  92577. for (var i = 0, j = 0; i < data.length; i++) {
  92578. data[i] += babylonVertexData.tangents[j++];
  92579. if ((i + 1) % 3 == 0) {
  92580. j++;
  92581. }
  92582. }
  92583. babylonMorphTarget.setTangents(data);
  92584. }
  92585. });
  92586. return Promise.all(promises).then(function () { });
  92587. };
  92588. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92589. if (accessor.componentType == 5126 /* FLOAT */) {
  92590. return data;
  92591. }
  92592. var factor = 1;
  92593. if (accessor.normalized) {
  92594. switch (accessor.componentType) {
  92595. case 5121 /* UNSIGNED_BYTE */: {
  92596. factor = 1 / 255;
  92597. break;
  92598. }
  92599. case 5123 /* UNSIGNED_SHORT */: {
  92600. factor = 1 / 65535;
  92601. break;
  92602. }
  92603. default: {
  92604. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92605. }
  92606. }
  92607. }
  92608. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92609. for (var i = 0; i < result.length; i++) {
  92610. result[i] = data[i] * factor;
  92611. }
  92612. return result;
  92613. };
  92614. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92615. var result = new Float32Array(data.length / 3 * 4);
  92616. var offset = 0;
  92617. for (var i = 0; i < result.length; i++) {
  92618. if ((i + 1) % 4 === 0) {
  92619. result[i] = 1;
  92620. }
  92621. else {
  92622. result[i] = data[offset++];
  92623. }
  92624. }
  92625. return result;
  92626. };
  92627. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92628. var position = BABYLON.Vector3.Zero();
  92629. var rotation = BABYLON.Quaternion.Identity();
  92630. var scaling = BABYLON.Vector3.One();
  92631. if (node.matrix) {
  92632. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92633. matrix.decompose(scaling, rotation, position);
  92634. }
  92635. else {
  92636. if (node.translation)
  92637. position = BABYLON.Vector3.FromArray(node.translation);
  92638. if (node.rotation)
  92639. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92640. if (node.scale)
  92641. scaling = BABYLON.Vector3.FromArray(node.scale);
  92642. }
  92643. babylonNode.position = position;
  92644. babylonNode.rotationQuaternion = rotation;
  92645. babylonNode.scaling = scaling;
  92646. };
  92647. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92648. var _this = this;
  92649. var assignSkeleton = function () {
  92650. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92651. var babylonMesh = _a[_i];
  92652. babylonMesh.skeleton = skin._babylonSkeleton;
  92653. }
  92654. node._babylonMesh.parent = _this._rootBabylonMesh;
  92655. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92656. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92657. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92658. };
  92659. if (skin._loaded) {
  92660. return skin._loaded.then(function () {
  92661. assignSkeleton();
  92662. });
  92663. }
  92664. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  92665. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  92666. var skeletonId = "skeleton" + skin._index;
  92667. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  92668. skin._babylonSkeleton = babylonSkeleton;
  92669. _this._loadBones(context, skin, inverseBindMatricesData);
  92670. assignSkeleton();
  92671. }));
  92672. };
  92673. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  92674. if (skin.inverseBindMatrices == undefined) {
  92675. return Promise.resolve(null);
  92676. }
  92677. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  92678. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92679. return data;
  92680. });
  92681. };
  92682. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  92683. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  92684. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92685. node._babylonAnimationTargets.push(babylonBone);
  92686. return babylonBone;
  92687. };
  92688. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  92689. var babylonBones = {};
  92690. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  92691. var index = _a[_i];
  92692. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  92693. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  92694. }
  92695. };
  92696. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  92697. var babylonBone = babylonBones[node._index];
  92698. if (babylonBone) {
  92699. return babylonBone;
  92700. }
  92701. var boneIndex = skin.joints.indexOf(node._index);
  92702. var baseMatrix = BABYLON.Matrix.Identity();
  92703. if (inverseBindMatricesData && boneIndex !== -1) {
  92704. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  92705. baseMatrix.invertToRef(baseMatrix);
  92706. }
  92707. var babylonParentBone = null;
  92708. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  92709. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  92710. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  92711. }
  92712. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  92713. babylonBones[node._index] = babylonBone;
  92714. return babylonBone;
  92715. };
  92716. GLTFLoader.prototype._getNodeMatrix = function (node) {
  92717. return node.matrix ?
  92718. BABYLON.Matrix.FromArray(node.matrix) :
  92719. 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());
  92720. };
  92721. GLTFLoader.prototype._loadAnimationsAsync = function () {
  92722. var animations = this._gltf.animations;
  92723. if (!animations) {
  92724. return Promise.resolve();
  92725. }
  92726. var promises = new Array();
  92727. for (var index = 0; index < animations.length; index++) {
  92728. var animation = animations[index];
  92729. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  92730. }
  92731. return Promise.all(promises).then(function () { });
  92732. };
  92733. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  92734. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  92735. animation._babylonAnimationGroup = babylonAnimationGroup;
  92736. var promises = new Array();
  92737. GLTF2.ArrayItem.Assign(animation.channels);
  92738. GLTF2.ArrayItem.Assign(animation.samplers);
  92739. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  92740. var channel = _a[_i];
  92741. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  92742. }
  92743. return Promise.all(promises).then(function () {
  92744. babylonAnimationGroup.normalize();
  92745. });
  92746. };
  92747. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  92748. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  92749. if (!targetNode._babylonMesh) {
  92750. return Promise.resolve();
  92751. }
  92752. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  92753. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  92754. var targetPath;
  92755. var animationType;
  92756. switch (channel.target.path) {
  92757. case "translation" /* TRANSLATION */: {
  92758. targetPath = "position";
  92759. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92760. break;
  92761. }
  92762. case "rotation" /* ROTATION */: {
  92763. targetPath = "rotationQuaternion";
  92764. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92765. break;
  92766. }
  92767. case "scale" /* SCALE */: {
  92768. targetPath = "scaling";
  92769. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92770. break;
  92771. }
  92772. case "weights" /* WEIGHTS */: {
  92773. targetPath = "influence";
  92774. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  92775. break;
  92776. }
  92777. default: {
  92778. throw new Error(context + ": Invalid target path " + channel.target.path);
  92779. }
  92780. }
  92781. var outputBufferOffset = 0;
  92782. var getNextOutputValue;
  92783. switch (targetPath) {
  92784. case "position": {
  92785. getNextOutputValue = function () {
  92786. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92787. outputBufferOffset += 3;
  92788. return value;
  92789. };
  92790. break;
  92791. }
  92792. case "rotationQuaternion": {
  92793. getNextOutputValue = function () {
  92794. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  92795. outputBufferOffset += 4;
  92796. return value;
  92797. };
  92798. break;
  92799. }
  92800. case "scaling": {
  92801. getNextOutputValue = function () {
  92802. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92803. outputBufferOffset += 3;
  92804. return value;
  92805. };
  92806. break;
  92807. }
  92808. case "influence": {
  92809. getNextOutputValue = function () {
  92810. var value = new Array(targetNode._numMorphTargets);
  92811. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  92812. value[i] = data.output[outputBufferOffset++];
  92813. }
  92814. return value;
  92815. };
  92816. break;
  92817. }
  92818. }
  92819. var getNextKey;
  92820. switch (data.interpolation) {
  92821. case "STEP" /* STEP */: {
  92822. getNextKey = function (frameIndex) { return ({
  92823. frame: data.input[frameIndex],
  92824. value: getNextOutputValue(),
  92825. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  92826. }); };
  92827. break;
  92828. }
  92829. case "LINEAR" /* LINEAR */: {
  92830. getNextKey = function (frameIndex) { return ({
  92831. frame: data.input[frameIndex],
  92832. value: getNextOutputValue()
  92833. }); };
  92834. break;
  92835. }
  92836. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92837. getNextKey = function (frameIndex) { return ({
  92838. frame: data.input[frameIndex],
  92839. inTangent: getNextOutputValue(),
  92840. value: getNextOutputValue(),
  92841. outTangent: getNextOutputValue()
  92842. }); };
  92843. break;
  92844. }
  92845. }
  92846. var keys;
  92847. if (data.input.length === 1) {
  92848. var key = getNextKey(0);
  92849. keys = [
  92850. { frame: key.frame, value: key.value },
  92851. { frame: key.frame + 1, value: key.value }
  92852. ];
  92853. }
  92854. else {
  92855. keys = new Array(data.input.length);
  92856. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  92857. keys[frameIndex] = getNextKey(frameIndex);
  92858. }
  92859. }
  92860. if (targetPath === "influence") {
  92861. var _loop_1 = function (targetIndex) {
  92862. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92863. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92864. babylonAnimation.setKeys(keys.map(function (key) { return ({
  92865. frame: key.frame,
  92866. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  92867. value: key.value[targetIndex],
  92868. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  92869. }); }));
  92870. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92871. var babylonMesh = _a[_i];
  92872. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  92873. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  92874. }
  92875. };
  92876. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  92877. _loop_1(targetIndex);
  92878. }
  92879. }
  92880. else {
  92881. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92882. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92883. babylonAnimation.setKeys(keys);
  92884. if (targetNode._babylonAnimationTargets) {
  92885. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  92886. var target = _a[_i];
  92887. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  92888. }
  92889. }
  92890. }
  92891. });
  92892. };
  92893. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  92894. if (sampler._data) {
  92895. return sampler._data;
  92896. }
  92897. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  92898. switch (interpolation) {
  92899. case "STEP" /* STEP */:
  92900. case "LINEAR" /* LINEAR */:
  92901. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92902. break;
  92903. }
  92904. default: {
  92905. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  92906. }
  92907. }
  92908. var inputData;
  92909. var outputData;
  92910. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  92911. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  92912. sampler._data = Promise.all([
  92913. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  92914. inputData = data;
  92915. }),
  92916. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  92917. outputData = data;
  92918. })
  92919. ]).then(function () {
  92920. return {
  92921. input: inputData,
  92922. interpolation: interpolation,
  92923. output: outputData,
  92924. };
  92925. });
  92926. return sampler._data;
  92927. };
  92928. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  92929. if (buffer._data) {
  92930. return buffer._data;
  92931. }
  92932. if (!buffer.uri) {
  92933. throw new Error(context + ": Uri is missing");
  92934. }
  92935. buffer._data = this._loadUriAsync(context, buffer.uri);
  92936. return buffer._data;
  92937. };
  92938. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  92939. if (bufferView._data) {
  92940. return bufferView._data;
  92941. }
  92942. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  92943. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  92944. try {
  92945. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  92946. }
  92947. catch (e) {
  92948. throw new Error(context + ": " + e.message);
  92949. }
  92950. });
  92951. return bufferView._data;
  92952. };
  92953. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  92954. var _this = this;
  92955. if (accessor.sparse) {
  92956. throw new Error(context + ": Sparse accessors are not currently supported");
  92957. }
  92958. if (accessor._data) {
  92959. return accessor._data;
  92960. }
  92961. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  92962. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  92963. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  92964. var byteOffset = accessor.byteOffset || 0;
  92965. var byteStride = bufferView.byteStride;
  92966. if (byteStride === 0) {
  92967. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  92968. }
  92969. try {
  92970. switch (accessor.componentType) {
  92971. case 5120 /* BYTE */: {
  92972. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92973. }
  92974. case 5121 /* UNSIGNED_BYTE */: {
  92975. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92976. }
  92977. case 5122 /* SHORT */: {
  92978. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92979. }
  92980. case 5123 /* UNSIGNED_SHORT */: {
  92981. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92982. }
  92983. case 5125 /* UNSIGNED_INT */: {
  92984. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92985. }
  92986. case 5126 /* FLOAT */: {
  92987. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  92988. }
  92989. default: {
  92990. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92991. }
  92992. }
  92993. }
  92994. catch (e) {
  92995. throw new Error(context + ": " + e);
  92996. }
  92997. });
  92998. return accessor._data;
  92999. };
  93000. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93001. byteOffset += data.byteOffset;
  93002. var targetLength = count * numComponents;
  93003. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93004. return new typedArray(data.buffer, byteOffset, targetLength);
  93005. }
  93006. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93007. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93008. var targetBuffer = new typedArray(targetLength);
  93009. var sourceIndex = 0;
  93010. var targetIndex = 0;
  93011. while (targetIndex < targetLength) {
  93012. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93013. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93014. targetIndex++;
  93015. }
  93016. sourceIndex += elementStride;
  93017. }
  93018. return targetBuffer;
  93019. };
  93020. GLTFLoader.prototype._getDefaultMaterial = function () {
  93021. var id = "__gltf_default";
  93022. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93023. if (!babylonMaterial) {
  93024. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93025. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93026. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93027. babylonMaterial.metallic = 1;
  93028. babylonMaterial.roughness = 1;
  93029. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93030. }
  93031. return babylonMaterial;
  93032. };
  93033. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93034. var promises = new Array();
  93035. var babylonMaterial = material._babylonMaterial;
  93036. // Ensure metallic workflow
  93037. babylonMaterial.metallic = 1;
  93038. babylonMaterial.roughness = 1;
  93039. var properties = material.pbrMetallicRoughness;
  93040. if (properties) {
  93041. if (properties.baseColorFactor) {
  93042. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93043. babylonMaterial.alpha = properties.baseColorFactor[3];
  93044. }
  93045. else {
  93046. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93047. }
  93048. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93049. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93050. if (properties.baseColorTexture) {
  93051. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93052. babylonMaterial.albedoTexture = texture;
  93053. }));
  93054. }
  93055. if (properties.metallicRoughnessTexture) {
  93056. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93057. babylonMaterial.metallicTexture = texture;
  93058. }));
  93059. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93060. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93061. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93062. }
  93063. }
  93064. this._loadMaterialAlphaProperties(context, material);
  93065. return Promise.all(promises).then(function () { });
  93066. };
  93067. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93068. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  93069. if (promise) {
  93070. return promise;
  93071. }
  93072. material._babylonMeshes = material._babylonMeshes || [];
  93073. material._babylonMeshes.push(babylonMesh);
  93074. if (material._loaded) {
  93075. babylonMesh.material = material._babylonMaterial;
  93076. return material._loaded;
  93077. }
  93078. var promises = new Array();
  93079. var babylonMaterial = this._createMaterial(material);
  93080. material._babylonMaterial = babylonMaterial;
  93081. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93082. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93083. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93084. babylonMesh.material = babylonMaterial;
  93085. return (material._loaded = Promise.all(promises).then(function () { }));
  93086. };
  93087. GLTFLoader.prototype._createMaterial = function (material) {
  93088. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93089. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93090. return babylonMaterial;
  93091. };
  93092. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93093. var promises = new Array();
  93094. var babylonMaterial = material._babylonMaterial;
  93095. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93096. if (material.doubleSided) {
  93097. babylonMaterial.backFaceCulling = false;
  93098. babylonMaterial.twoSidedLighting = true;
  93099. }
  93100. if (material.normalTexture) {
  93101. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93102. babylonMaterial.bumpTexture = texture;
  93103. }));
  93104. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93105. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93106. if (material.normalTexture.scale != undefined) {
  93107. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93108. }
  93109. }
  93110. if (material.occlusionTexture) {
  93111. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93112. babylonMaterial.ambientTexture = texture;
  93113. }));
  93114. babylonMaterial.useAmbientInGrayScale = true;
  93115. if (material.occlusionTexture.strength != undefined) {
  93116. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93117. }
  93118. }
  93119. if (material.emissiveTexture) {
  93120. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93121. babylonMaterial.emissiveTexture = texture;
  93122. }));
  93123. }
  93124. return Promise.all(promises).then(function () { });
  93125. };
  93126. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93127. var babylonMaterial = material._babylonMaterial;
  93128. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93129. switch (alphaMode) {
  93130. case "OPAQUE" /* OPAQUE */: {
  93131. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93132. break;
  93133. }
  93134. case "MASK" /* MASK */: {
  93135. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93136. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93137. if (babylonMaterial.alpha) {
  93138. if (babylonMaterial.alpha === 0) {
  93139. babylonMaterial.alphaCutOff = 1;
  93140. }
  93141. else {
  93142. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93143. }
  93144. babylonMaterial.alpha = 1;
  93145. }
  93146. if (babylonMaterial.albedoTexture) {
  93147. babylonMaterial.albedoTexture.hasAlpha = true;
  93148. }
  93149. break;
  93150. }
  93151. case "BLEND" /* BLEND */: {
  93152. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93153. if (babylonMaterial.albedoTexture) {
  93154. babylonMaterial.albedoTexture.hasAlpha = true;
  93155. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93156. }
  93157. break;
  93158. }
  93159. default: {
  93160. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  93161. }
  93162. }
  93163. };
  93164. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93165. var _this = this;
  93166. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93167. context = "#/textures/" + textureInfo.index;
  93168. var promises = new Array();
  93169. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93170. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93171. var deferred = new BABYLON.Deferred();
  93172. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93173. if (!_this._disposed) {
  93174. deferred.resolve();
  93175. }
  93176. }, function (message, exception) {
  93177. if (!_this._disposed) {
  93178. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  93179. }
  93180. });
  93181. promises.push(deferred.promise);
  93182. babylonTexture.name = texture.name || "texture" + texture._index;
  93183. babylonTexture.wrapU = samplerData.wrapU;
  93184. babylonTexture.wrapV = samplerData.wrapV;
  93185. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93186. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93187. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93188. babylonTexture.updateURL(objectURL);
  93189. }));
  93190. assign(babylonTexture);
  93191. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93192. return Promise.all(promises).then(function () { });
  93193. };
  93194. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93195. if (!sampler._data) {
  93196. sampler._data = {
  93197. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93198. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93199. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93200. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93201. };
  93202. }
  93203. ;
  93204. return sampler._data;
  93205. };
  93206. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93207. if (image._objectURL) {
  93208. return image._objectURL;
  93209. }
  93210. var promise;
  93211. if (image.uri) {
  93212. promise = this._loadUriAsync(context, image.uri);
  93213. }
  93214. else {
  93215. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93216. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93217. }
  93218. image._objectURL = promise.then(function (data) {
  93219. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93220. });
  93221. return image._objectURL;
  93222. };
  93223. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93224. var _this = this;
  93225. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93226. if (promise) {
  93227. return promise;
  93228. }
  93229. if (!GLTFLoader._ValidateUri(uri)) {
  93230. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93231. }
  93232. if (BABYLON.Tools.IsBase64(uri)) {
  93233. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93234. }
  93235. return new Promise(function (resolve, reject) {
  93236. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93237. if (!_this._disposed) {
  93238. resolve(new Uint8Array(data));
  93239. }
  93240. }, function (event) {
  93241. if (!_this._disposed) {
  93242. try {
  93243. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93244. request._lengthComputable = event.lengthComputable;
  93245. request._loaded = event.loaded;
  93246. request._total = event.total;
  93247. _this._onProgress();
  93248. }
  93249. }
  93250. catch (e) {
  93251. reject(e);
  93252. }
  93253. }
  93254. }, _this._babylonScene.database, true, function (request, exception) {
  93255. if (!_this._disposed) {
  93256. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93257. }
  93258. });
  93259. _this._requests.push(request);
  93260. });
  93261. };
  93262. GLTFLoader.prototype._onProgress = function () {
  93263. if (!this._progressCallback) {
  93264. return;
  93265. }
  93266. var lengthComputable = true;
  93267. var loaded = 0;
  93268. var total = 0;
  93269. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93270. var request = _a[_i];
  93271. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93272. return;
  93273. }
  93274. lengthComputable = lengthComputable && request._lengthComputable;
  93275. loaded += request._loaded;
  93276. total += request._total;
  93277. }
  93278. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93279. };
  93280. GLTFLoader._GetProperty = function (context, array, index) {
  93281. if (!array || index == undefined || !array[index]) {
  93282. throw new Error(context + ": Failed to find index " + index);
  93283. }
  93284. return array[index];
  93285. };
  93286. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93287. // Set defaults if undefined
  93288. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93289. switch (mode) {
  93290. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93291. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93292. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93293. default:
  93294. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93295. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93296. }
  93297. };
  93298. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93299. // Set defaults if undefined
  93300. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93301. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93302. if (magFilter === 9729 /* LINEAR */) {
  93303. switch (minFilter) {
  93304. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93305. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93306. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93307. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93308. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93309. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93310. default:
  93311. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93312. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93313. }
  93314. }
  93315. else {
  93316. if (magFilter !== 9728 /* NEAREST */) {
  93317. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93318. }
  93319. switch (minFilter) {
  93320. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93321. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93322. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93323. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93324. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93325. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93326. default:
  93327. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93328. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93329. }
  93330. }
  93331. };
  93332. GLTFLoader._GetNumComponents = function (context, type) {
  93333. switch (type) {
  93334. case "SCALAR": return 1;
  93335. case "VEC2": return 2;
  93336. case "VEC3": return 3;
  93337. case "VEC4": return 4;
  93338. case "MAT2": return 4;
  93339. case "MAT3": return 9;
  93340. case "MAT4": return 16;
  93341. }
  93342. throw new Error(context + ": Invalid type " + type);
  93343. };
  93344. GLTFLoader._ValidateUri = function (uri) {
  93345. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93346. };
  93347. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93348. var promises = new Array();
  93349. if (this._gltf.materials) {
  93350. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93351. var material = _a[_i];
  93352. var babylonMaterial = material._babylonMaterial;
  93353. var babylonMeshes = material._babylonMeshes;
  93354. if (babylonMaterial && babylonMeshes) {
  93355. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93356. var babylonMesh = babylonMeshes_1[_b];
  93357. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93358. if (this.useClipPlane) {
  93359. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93360. }
  93361. }
  93362. }
  93363. }
  93364. }
  93365. return Promise.all(promises).then(function () { });
  93366. };
  93367. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93368. var promises = new Array();
  93369. var lights = this._babylonScene.lights;
  93370. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93371. var light = lights_1[_i];
  93372. var generator = light.getShadowGenerator();
  93373. if (generator) {
  93374. promises.push(generator.forceCompilationAsync());
  93375. }
  93376. }
  93377. return Promise.all(promises).then(function () { });
  93378. };
  93379. GLTFLoader.prototype._clear = function () {
  93380. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93381. var request = _a[_i];
  93382. request.abort();
  93383. }
  93384. this._requests.length = 0;
  93385. if (this._gltf && this._gltf.images) {
  93386. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93387. var image = _c[_b];
  93388. if (image._objectURL) {
  93389. image._objectURL.then(function (value) {
  93390. URL.revokeObjectURL(value);
  93391. });
  93392. image._objectURL = undefined;
  93393. }
  93394. }
  93395. }
  93396. delete this._gltf;
  93397. delete this._babylonScene;
  93398. this._completePromises.length = 0;
  93399. for (var name_3 in this._extensions) {
  93400. this._extensions[name_3].dispose();
  93401. }
  93402. this._extensions = {};
  93403. delete this._rootBabylonMesh;
  93404. delete this._progressCallback;
  93405. this.onMeshLoadedObservable.clear();
  93406. this.onTextureLoadedObservable.clear();
  93407. this.onMaterialLoadedObservable.clear();
  93408. };
  93409. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93410. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93411. var name_4 = _a[_i];
  93412. var extension = this._extensions[name_4];
  93413. if (extension.enabled) {
  93414. var promise = actionAsync(extension);
  93415. if (promise) {
  93416. return promise;
  93417. }
  93418. }
  93419. }
  93420. return null;
  93421. };
  93422. GLTFLoader._Names = new Array();
  93423. GLTFLoader._Factories = {};
  93424. return GLTFLoader;
  93425. }());
  93426. GLTF2.GLTFLoader = GLTFLoader;
  93427. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93428. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93429. })(BABYLON || (BABYLON = {}));
  93430. //# sourceMappingURL=babylon.glTFLoader.js.map
  93431. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93432. var BABYLON;
  93433. (function (BABYLON) {
  93434. var GLTF2;
  93435. (function (GLTF2) {
  93436. var GLTFLoaderExtension = /** @class */ (function () {
  93437. function GLTFLoaderExtension(loader) {
  93438. this.enabled = true;
  93439. this._loader = loader;
  93440. }
  93441. GLTFLoaderExtension.prototype.dispose = function () {
  93442. delete this._loader;
  93443. };
  93444. // #region Overridable Methods
  93445. /** Override this method to modify the default behavior for loading scenes. */
  93446. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93447. /** Override this method to modify the default behavior for loading nodes. */
  93448. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93449. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93450. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93451. /** Override this method to modify the default behavior for loading materials. */
  93452. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  93453. /** Override this method to modify the default behavior for loading uris. */
  93454. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93455. // #endregion
  93456. /** Helper method called by a loader extension to load an glTF extension. */
  93457. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93458. if (!property.extensions) {
  93459. return null;
  93460. }
  93461. var extensions = property.extensions;
  93462. var extension = extensions[this.name];
  93463. if (!extension) {
  93464. return null;
  93465. }
  93466. // Clear out the extension before executing the action to avoid recursing into the same property.
  93467. delete extensions[this.name];
  93468. try {
  93469. return actionAsync(context + "/extensions/" + this.name, extension);
  93470. }
  93471. finally {
  93472. // Restore the extension after executing the action.
  93473. extensions[this.name] = extension;
  93474. }
  93475. };
  93476. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93477. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93478. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93479. };
  93480. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93481. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93482. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93483. };
  93484. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93485. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93486. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93487. };
  93488. /** Helper method called by the loader to allow extensions to override loading materials. */
  93489. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  93490. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  93491. };
  93492. /** Helper method called by the loader to allow extensions to override loading uris. */
  93493. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93494. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93495. };
  93496. return GLTFLoaderExtension;
  93497. }());
  93498. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93499. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93500. })(BABYLON || (BABYLON = {}));
  93501. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93502. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93503. var BABYLON;
  93504. (function (BABYLON) {
  93505. var GLTF2;
  93506. (function (GLTF2) {
  93507. var Extensions;
  93508. (function (Extensions) {
  93509. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93510. var NAME = "MSFT_lod";
  93511. var MSFT_lod = /** @class */ (function (_super) {
  93512. __extends(MSFT_lod, _super);
  93513. function MSFT_lod() {
  93514. var _this = _super !== null && _super.apply(this, arguments) || this;
  93515. _this.name = NAME;
  93516. /**
  93517. * Maximum number of LODs to load, starting from the lowest LOD.
  93518. */
  93519. _this.maxLODsToLoad = Number.MAX_VALUE;
  93520. _this._loadingNodeLOD = null;
  93521. _this._loadNodeSignals = {};
  93522. _this._loadingMaterialLOD = null;
  93523. _this._loadMaterialSignals = {};
  93524. return _this;
  93525. }
  93526. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93527. var _this = this;
  93528. return this._loadExtensionAsync(context, node, function (context, extension) {
  93529. var firstPromise;
  93530. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93531. var _loop_1 = function (indexLOD) {
  93532. var nodeLOD = nodeLODs[indexLOD];
  93533. if (indexLOD !== 0) {
  93534. _this._loadingNodeLOD = nodeLOD;
  93535. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93536. }
  93537. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93538. if (indexLOD !== 0) {
  93539. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93540. previousNodeLOD._babylonMesh.setEnabled(false);
  93541. }
  93542. if (indexLOD !== nodeLODs.length - 1) {
  93543. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93544. _this._loadNodeSignals[nodeIndex].resolve();
  93545. delete _this._loadNodeSignals[nodeIndex];
  93546. }
  93547. });
  93548. if (indexLOD === 0) {
  93549. firstPromise = promise;
  93550. }
  93551. else {
  93552. _this._loader._completePromises.push(promise);
  93553. _this._loadingNodeLOD = null;
  93554. }
  93555. };
  93556. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93557. _loop_1(indexLOD);
  93558. }
  93559. return firstPromise;
  93560. });
  93561. };
  93562. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93563. var _this = this;
  93564. // Don't load material LODs if already loading a node LOD.
  93565. if (this._loadingNodeLOD) {
  93566. return null;
  93567. }
  93568. return this._loadExtensionAsync(context, material, function (context, extension) {
  93569. var firstPromise;
  93570. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93571. var _loop_2 = function (indexLOD) {
  93572. var materialLOD = materialLODs[indexLOD];
  93573. if (indexLOD !== 0) {
  93574. _this._loadingMaterialLOD = materialLOD;
  93575. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93576. }
  93577. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  93578. if (indexLOD !== materialLODs.length - 1) {
  93579. var materialIndex = materialLODs[indexLOD + 1]._index;
  93580. _this._loadMaterialSignals[materialIndex].resolve();
  93581. delete _this._loadMaterialSignals[materialIndex];
  93582. }
  93583. });
  93584. if (indexLOD === 0) {
  93585. firstPromise = promise;
  93586. }
  93587. else {
  93588. _this._loader._completePromises.push(promise);
  93589. _this._loadingMaterialLOD = null;
  93590. }
  93591. };
  93592. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93593. _loop_2(indexLOD);
  93594. }
  93595. return firstPromise;
  93596. });
  93597. };
  93598. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93599. var _this = this;
  93600. // Defer the loading of uris if loading a material or node LOD.
  93601. if (this._loadingMaterialLOD) {
  93602. var index = this._loadingMaterialLOD._index;
  93603. return this._loadMaterialSignals[index].promise.then(function () {
  93604. return _this._loader._loadUriAsync(context, uri);
  93605. });
  93606. }
  93607. else if (this._loadingNodeLOD) {
  93608. var index = this._loadingNodeLOD._index;
  93609. return this._loadNodeSignals[index].promise.then(function () {
  93610. return _this._loader._loadUriAsync(context, uri);
  93611. });
  93612. }
  93613. return null;
  93614. };
  93615. /**
  93616. * Gets an array of LOD properties from lowest to highest.
  93617. */
  93618. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93619. if (this.maxLODsToLoad <= 0) {
  93620. throw new Error("maxLODsToLoad must be greater than zero");
  93621. }
  93622. var properties = new Array();
  93623. for (var i = ids.length - 1; i >= 0; i--) {
  93624. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93625. if (properties.length === this.maxLODsToLoad) {
  93626. return properties;
  93627. }
  93628. }
  93629. properties.push(property);
  93630. return properties;
  93631. };
  93632. return MSFT_lod;
  93633. }(GLTF2.GLTFLoaderExtension));
  93634. Extensions.MSFT_lod = MSFT_lod;
  93635. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93636. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93637. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93638. })(BABYLON || (BABYLON = {}));
  93639. //# sourceMappingURL=MSFT_lod.js.map
  93640. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93641. var BABYLON;
  93642. (function (BABYLON) {
  93643. var GLTF2;
  93644. (function (GLTF2) {
  93645. var Extensions;
  93646. (function (Extensions) {
  93647. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93648. var NAME = "KHR_draco_mesh_compression";
  93649. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93650. __extends(KHR_draco_mesh_compression, _super);
  93651. function KHR_draco_mesh_compression(loader) {
  93652. var _this = _super.call(this, loader) || this;
  93653. _this.name = NAME;
  93654. _this._dracoCompression = null;
  93655. // Disable extension if decoder is not available.
  93656. if (!BABYLON.DracoCompression.DecoderUrl) {
  93657. _this.enabled = false;
  93658. }
  93659. return _this;
  93660. }
  93661. KHR_draco_mesh_compression.prototype.dispose = function () {
  93662. if (this._dracoCompression) {
  93663. this._dracoCompression.dispose();
  93664. }
  93665. _super.prototype.dispose.call(this);
  93666. };
  93667. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93668. var _this = this;
  93669. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  93670. if (primitive.mode != undefined) {
  93671. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  93672. primitive.mode !== 4 /* TRIANGLES */) {
  93673. throw new Error(context + ": Unsupported mode " + primitive.mode);
  93674. }
  93675. // TODO: handle triangle strips
  93676. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  93677. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  93678. }
  93679. }
  93680. var attributes = {};
  93681. var loadAttribute = function (name, kind) {
  93682. var uniqueId = extension.attributes[name];
  93683. if (uniqueId == undefined) {
  93684. return;
  93685. }
  93686. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93687. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93688. babylonMesh._delayInfo.push(kind);
  93689. }
  93690. attributes[kind] = uniqueId;
  93691. };
  93692. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93693. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93694. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93695. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93696. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93697. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93698. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93699. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93700. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  93701. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  93702. try {
  93703. if (!_this._dracoCompression) {
  93704. _this._dracoCompression = new BABYLON.DracoCompression();
  93705. }
  93706. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  93707. }
  93708. catch (e) {
  93709. throw new Error(context + ": " + e.message);
  93710. }
  93711. });
  93712. });
  93713. };
  93714. return KHR_draco_mesh_compression;
  93715. }(GLTF2.GLTFLoaderExtension));
  93716. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  93717. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  93718. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93719. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93720. })(BABYLON || (BABYLON = {}));
  93721. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  93722. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93723. var BABYLON;
  93724. (function (BABYLON) {
  93725. var GLTF2;
  93726. (function (GLTF2) {
  93727. var Extensions;
  93728. (function (Extensions) {
  93729. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  93730. var NAME = "KHR_materials_pbrSpecularGlossiness";
  93731. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  93732. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  93733. function KHR_materials_pbrSpecularGlossiness() {
  93734. var _this = _super !== null && _super.apply(this, arguments) || this;
  93735. _this.name = NAME;
  93736. return _this;
  93737. }
  93738. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93739. var _this = this;
  93740. return this._loadExtensionAsync(context, material, function (context, extension) {
  93741. material._babylonMeshes = material._babylonMeshes || [];
  93742. material._babylonMeshes.push(babylonMesh);
  93743. if (material._loaded) {
  93744. babylonMesh.material = material._babylonMaterial;
  93745. return material._loaded;
  93746. }
  93747. var promises = new Array();
  93748. var babylonMaterial = _this._loader._createMaterial(material);
  93749. material._babylonMaterial = babylonMaterial;
  93750. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  93751. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  93752. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93753. babylonMesh.material = babylonMaterial;
  93754. return (material._loaded = Promise.all(promises).then(function () { }));
  93755. });
  93756. };
  93757. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  93758. var promises = new Array();
  93759. var babylonMaterial = material._babylonMaterial;
  93760. if (properties.diffuseFactor) {
  93761. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  93762. babylonMaterial.alpha = properties.diffuseFactor[3];
  93763. }
  93764. else {
  93765. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93766. }
  93767. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  93768. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  93769. if (properties.diffuseTexture) {
  93770. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  93771. babylonMaterial.albedoTexture = texture;
  93772. }));
  93773. }
  93774. if (properties.specularGlossinessTexture) {
  93775. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  93776. babylonMaterial.reflectivityTexture = texture;
  93777. }));
  93778. babylonMaterial.reflectivityTexture.hasAlpha = true;
  93779. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  93780. }
  93781. loader._loadMaterialAlphaProperties(context, material);
  93782. return Promise.all(promises).then(function () { });
  93783. };
  93784. return KHR_materials_pbrSpecularGlossiness;
  93785. }(GLTF2.GLTFLoaderExtension));
  93786. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  93787. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  93788. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93789. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93790. })(BABYLON || (BABYLON = {}));
  93791. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  93792. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93793. var BABYLON;
  93794. (function (BABYLON) {
  93795. var GLTF2;
  93796. (function (GLTF2) {
  93797. var Extensions;
  93798. (function (Extensions) {
  93799. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  93800. var NAME = "KHR_lights";
  93801. var LightType;
  93802. (function (LightType) {
  93803. LightType["AMBIENT"] = "ambient";
  93804. LightType["DIRECTIONAL"] = "directional";
  93805. LightType["POINT"] = "point";
  93806. LightType["SPOT"] = "spot";
  93807. })(LightType || (LightType = {}));
  93808. var KHR_lights = /** @class */ (function (_super) {
  93809. __extends(KHR_lights, _super);
  93810. function KHR_lights() {
  93811. var _this = _super !== null && _super.apply(this, arguments) || this;
  93812. _this.name = NAME;
  93813. return _this;
  93814. }
  93815. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  93816. var _this = this;
  93817. return this._loadExtensionAsync(context, scene, function (context, extension) {
  93818. var promise = _this._loader._loadSceneAsync(context, scene);
  93819. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93820. if (light.type !== LightType.AMBIENT) {
  93821. throw new Error(context + ": Only ambient lights are allowed on a scene");
  93822. }
  93823. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  93824. return promise;
  93825. });
  93826. };
  93827. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  93828. var _this = this;
  93829. return this._loadExtensionAsync(context, node, function (context, extension) {
  93830. var promise = _this._loader._loadNodeAsync(context, node);
  93831. var babylonLight;
  93832. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93833. var name = node._babylonMesh.name;
  93834. switch (light.type) {
  93835. case LightType.AMBIENT: {
  93836. throw new Error(context + ": Ambient lights are not allowed on a node");
  93837. }
  93838. case LightType.DIRECTIONAL: {
  93839. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  93840. break;
  93841. }
  93842. case LightType.POINT: {
  93843. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  93844. break;
  93845. }
  93846. case LightType.SPOT: {
  93847. var spotLight = light;
  93848. // TODO: support inner and outer cone angles
  93849. //const innerConeAngle = spotLight.innerConeAngle || 0;
  93850. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  93851. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  93852. break;
  93853. }
  93854. default: {
  93855. throw new Error(context + ": Invalid light type " + light.type);
  93856. }
  93857. }
  93858. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  93859. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  93860. babylonLight.parent = node._babylonMesh;
  93861. return promise;
  93862. });
  93863. };
  93864. Object.defineProperty(KHR_lights.prototype, "_lights", {
  93865. get: function () {
  93866. var extensions = this._loader._gltf.extensions;
  93867. if (!extensions || !extensions[this.name]) {
  93868. throw new Error("#/extensions: " + this.name + " not found");
  93869. }
  93870. var extension = extensions[this.name];
  93871. return extension.lights;
  93872. },
  93873. enumerable: true,
  93874. configurable: true
  93875. });
  93876. return KHR_lights;
  93877. }(GLTF2.GLTFLoaderExtension));
  93878. Extensions.KHR_lights = KHR_lights;
  93879. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  93880. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93881. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93882. })(BABYLON || (BABYLON = {}));
  93883. //# sourceMappingURL=KHR_lights.js.map
  93884. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  93885. globalObject["BABYLON"] = BABYLON
  93886. return BABYLON;
  93887. });